MongoDB Python驱动
admin
2023-04-12 14:21:25
0

使用pip install pymongo安装

1.连接MongoDB实例

In [60]: from pymongo import MongoClient

In [61]: client=MongoClient('mongodb://10.10.41.25:2911')

In [62]: client=MongoClient('10.10.41.25',2911)

两种写法都行


2.获取数据库信息

In [63]: db=client.game

In [64]: db=client['game']

两种写法都行


3.获取集合信息

In [85]: collection=db.player

In [86]: collection=db['player']

两种写法都行


4.插入一个文档记录

MongoDB以JSON格式存储和显示数据。在pymongo中以字典的方式显示数据。

In [95]: import datetime

In [96]: post={"author":"Mike","text":"My first blog post!","tags":["mongodb","python","pymongo"],"date":datetime.datetime.utcnow()}
In [132]: posts=db.posts

In [133]: post_id=posts.insert(post)

In [134]: post_id
Out[134]: ObjectId('550ad8677a50900165feae9d')


当插入一个文档时,一个特殊的key,"_id"将自动添加到这个文档中。

In [136]: db.collection_names()
Out[136]: 
[u'system.indexes',u'posts']


5.使用find_one()获取单个文档

In [141]: posts.find_one()
Out[141]: 
{u'_id': ObjectId('550ad8677a50900165feae9d'),
 u'author': u'Mike',
 u'date': datetime.datetime(2015, 3, 19, 14, 7, 14, 572000),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

In [142]: posts.find_one({"author":"Mike"})
Out[142]: 
{u'_id': ObjectId('550ad8677a50900165feae9d'),
 u'author': u'Mike',
 u'date': datetime.datetime(2015, 3, 19, 14, 7, 14, 572000),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

In [143]: posts.find_one({"author":"Eliot"})

In [144]:


MongoDB以BSON格式存储字符,而BSON字符串是以UTF-8编码,所以PyMongo必须要确保它存储的数据是有效的UTF-8编码的数据。常规字符串直接存储,但是经过编码的字符串首先以UTF-8编码存储。




6.使用ObjectID查找文档

In [151]: post_id
Out[151]: ObjectId('550ad8677a50900165feae9d')

In [152]: posts.find_one({"_id":post_id})
Out[152]: 
{u'_id': ObjectId('550ad8677a50900165feae9d'),
 u'author': u'Mike',
 u'date': datetime.datetime(2015, 3, 19, 14, 7, 14, 572000),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

ObjectID和它表示的字符串不一样

In [154]: post_id_as_str=str(post_id)

In [155]: posts.find_one({"_id":post_id_as_str})

没有任何结果显示


在一些WEB应用中,需要更加URL获取post_id进而根据post_id查找匹配的文档。在使用find_one()查找之前有必要将post_id从字符串转换成为ObjectID



7.批量插入文档数据

>>> 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('...')]


8.查询多个文档数据

In [165]: for post in posts.find():
          post
   .....:     
   .....:     
Out[166]: 
{u'_id': ObjectId('550ad8677a50900165feae9d'),
 u'author': u'Mike',
 u'date': datetime.datetime(2015, 3, 19, 14, 7, 14, 572000),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}
Out[166]: 
{u'_id': ObjectId('550b87d47a50907021e3473b'),
 u'author': u'Mike',
 u'date': datetime.datetime(2009, 11, 12, 11, 14),
 u'text': u'Another post!'}
Out[166]: 
{u'_id': ObjectId('550b87d47a50907021e3473c'),
 u'author': u'Eliot',
 u'title': u'MongoDB is fun'}
In [169]: for post in posts.find({"author" : "Mike"}):
   .....:     post
   .....:     
   .....:     
Out[169]: 
{u'_id': ObjectId('550ad8677a50900165feae9d'),
 u'author': u'Mike',
 u'date': datetime.datetime(2015, 3, 19, 14, 7, 14, 572000),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}
Out[169]: 
{u'_id': ObjectId('550b87d47a50907021e3473b'),
 u'author': u'Mike',
 u'date': datetime.datetime(2009, 11, 12, 11, 14),
 u'text': u'Another post!'}


9.总计

In [170]: posts.count()
Out[170]: 3

In [171]: posts.find({"author":"Mike"}).count()
Out[171]: 2


10.范围查询

In [183]: d=datetime.datetime(2009,11,12,12)

In [184]: for post in posts.find({"date":{"$lt":d}}).sort("author"):
   .....:     print post
   .....:     
   .....:     
{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('550b87d47a50907021e3473b'), u'author': u'Mike'}


11.索引

使用索引可以加快查询速度,缩小查询范围。

In [201]: posts.find({"date" : {"$lt":d}}).sort("author").explain()["cursor"]
Out[201]: u'BasicCursor'

In [202]: posts.find({"date" : {"$lt":d}}).sort("author").explain()["nscanned"]
Out[202]: 3


创建组合索引

In [241]: from pymongo import ASCENDING,DESCENDING

In [242]: posts.create_index([("date",DESCENDING),("author",ASCENDING)])
Out[242]: u'date_-1_author_1'

In [243]: posts.find({"date" : {"$lt":d}}).sort("author").explain()["nscanned"]
Out[243]: 1



12.



参考文档

http://api.mongodb.org/python/current/tutorial.html?_ga=1.58141740.722641156.1410499072


相关内容

热门资讯

AI会取代哪些职业?多个AI意... 当前,人们日益担忧人工智能(AI)将影响就业市场。美国近期一项研究显示,多个人工智能模型在预测哪些职...
大疆Air 4无人机曝光,预估... IT之家 5 月 12 日消息,消息源 Igor Bogdanov 昨日(5 月 11 日)在 X ...
中核国电漳州能源原党委书记、董... 中核集团中核国电漳州能源有限公司原党委书记、董事长何辉涉嫌严重违纪违法,目前正接受中央纪委国家监委驻...
总投资1.85亿元,郑州市金水... 【大河财立方消息】 5月11日,金水区人民政府对金水区城市更新项目入库信息进行公示,公示期为2026...
特朗普访华期间是否会讨论台湾和... 澎湃新闻记者 聂舒翼 谢瑞强5月12日,外交部发言人郭嘉昆主持例行记者会。有记者就特朗普访华期间是否...
AI+教育,郑州航空港区成果亮... 【大河财立方 记者 程帅星】5月11日,由教育部、浙江省人民政府共同主办的2026世界数字教育大会在...
外交部:中方反对美国向中国台湾... 新华社北京5月12日电(记者万倩仪、冯歆然)外交部发言人郭嘉昆12日在例行记者会上就中美关系和台湾问...
外交部:亚太各国应擦亮眼睛,共... 新华社北京5月12日电(记者董雪、孙楠)外交部发言人郭嘉昆5月12日在例行记者会上回答相关问题时表示...
坚定不移沿着习近平总书记指引的... 吴敏杰(右一)和陈萍(左一),由班车结缘。湖北日报全媒记者 张诗秋 摄淅川到柴湖的班车。李栀子 卢晋...
热搜爆了!腾讯张军: 不会开发... 5月11日晚,“微信状态 访客记录”爆上热搜第一。 今天(5月12日),微信员工@客村小蒋发文回应:...