Python调用MongoDB使用心得本文是一个Python 使用MongoDB的简单教程,将使用pymongo对MongoDB进行的各种操
Python调用MongoDB使用心得
本文是一个Python 使用MongoDB的简单教程,将使用pymongo对MongoDB进行的各种操作进行了简单的汇总,NoSQLFan进行了简单整理,使用Python的同学可以看一看。
下载相应平台的版本,解压即可。为方便使用,将bin路径添加到系统path环境变量里。其中mongod是服务器,mongo是客户shell,然后创建数据文件目录:在c盘下创建data文件夹,里面创建db文件夹。
基本使用:
?

?
安装对应语言的Driver,Python 安装 pymongo
?
$?easy_install?pymongo
?
使用方法总结,摘自官方教程
创建连接
?
>>>?import?pymongo?
>>>?connection=pymongo.Connection('localhost',27017)
?
切换数据库
?
>>>?db?=?connection.test_database
?
获取collection
?
>>>?collection?=?db.test_collection
?
db和collection都是延时创建的,在添加Document时才真正创建
文档添加,_id自动创建
?
>>>?import?datetime?
>>>?post?=?{"author":?"Mike",?
...?"text":?"My?first?blog?post!",?
...?"tags":?["mongodb",?"python",?"pymongo"],?
...?"date":?datetime.datetime.utcnow()}?
>>>?posts?=?db.posts?
>>>?posts.insert(post)?
ObjectId('...')
?
批量插入
?
>>>?new_posts?=?[{"author":?"Mike",?
...?"text":?"Another?post!",?
...?"tags":?["bulk",?"insert"],?
...?"date":?datetime.datetime(2009,?11,?12,?11,?14)},?
...?{"author":?"Eliot",?
...?"title":?"MongoDB?is?fun",?
...?"text":?"and?pretty?easy?too!",?
...?"date":?datetime.datetime(2009,?11,?10,?10,?45)}]?
>>>?posts.insert(new_posts)?
[ObjectId('...'),?ObjectId('...')]
?
获取所有collection(相当于SQL的show tables)
?
>>>?db.collection_names()?
[u'posts',?u'system.indexes']
?
获取单个文档
?
>>>?posts.find_one()?
{u'date':?datetime.datetime(...),?u'text':?u'My?first?blog?post!',?u'_id':?ObjectId('...'),?u'author':?u'Mike',?u'tags':?[u'mongodb',?u'python',?u'pymongo']}
?
查询多个文档
?
>>?for?post?in?posts.find():?
...?post?
...?
{u'date':?datetime.datetime(...),?u'text':?u'My?first?blog?post!',?u'_id':?ObjectId('...'),?u'author':?u'Mike',?u'tags':?[u'mongodb',?u'python',?u'pymongo']}?
{u'date':?datetime.datetime(2009,?11,?12,?11,?14),?u'text':?u'Another?post!',?u'_id':?ObjectId('...'),?u'author':?u'Mike',?u'tags':?[u'bulk',?u'insert']}?
{u'date':?datetime.datetime(2009,?11,?10,?10,?45),?u'text':?u'and?pretty?easy?too!',?u'_id':?ObjectId('...'),?u'author':?u'Eliot',?u'title':?u'MongoDB?is?fun'}
?
加条件的查询
?
>>>?posts.find_one({"author":?"Mike"})
?
高级查询
?
>>>?posts.find({"date":?{"$lt":?d}}).sort("author")
?
统计数量
?
>>>?posts.count()?
3
?
加索引
?
>>>?from?pymongo?import?ASCENDING,?DESCENDING?
>>>?posts.create_index([("date",?DESCENDING),?("author",?ASCENDING)])?
u'date_-1_author_1'
?
查看查询语句的性能
?
>>>?posts.find({"date":?{"$lt":?d}}).sort("author").explain()["cursor"]?
u'BtreeCursor?date_-1_author_1'?
>>>?posts.find({"date":?{"$lt":?d}}).sort("author").explain()["nscanned"]?
2
?
附自己总结的一点小心得,仅供参考
缺点