MongoDB Python驱动

发布时间:2019-08-07 13:52:57编辑:auto阅读(1377)

    使用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


关键字

上一篇: python写excel

下一篇: Python-wingide