MongoDB數據庫(6)__motor


2019.7.22:

 

motor是異步實現python操作數據庫的工具。能減少后端訪問數據庫的延遲。


Motor 是一個異步實現的 MongoDB 存儲庫 Motor 與 Pymongo 的配置基本類似。連接對象就由 MongoClient 變為 AsyncIOMotorClient 了。

 

一、連接

# 普通連接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017')
# 副本集連接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://host1,host2/?replicaSet=my-replicaset-name')
# 密碼連接
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://username:password@localhost:27017/dbname')
# 獲取數據庫
db = client.zfdb
# db = client['zfdb']
# 獲取 collection
collection = db.test
# collection = db['test']

 

二、添加一條記錄

async def do_insert():
     document = {'name': 'zone','sex':'boy'}
     result = await db.test_collection.insert_one(document)
     print('result %s' % repr(result.inserted_id))
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())

 

三、批量增加記錄

async def do_insert():
    result = await db.test_collection.insert_many(
        [{'name': i, 'sex': str(i + 2)} for i in range(20)])
    print('inserted %d docs' % (len(result.inserted_ids),))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())

 

四、查找一條記錄

async def do_find_one():
    document = await db.test_collection.find_one({'name': 'zone'})
    pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find_one())

 

五、查找多條記錄

async def do_find():
    cursor = db.test_collection.find({'name': {'$lt': 5}}).sort('i')
    for document in await cursor.to_list(length=100):
        pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())

# 添加篩選條件,排序、跳過、限制返回結果數
async def do_find():
    cursor = db.test_collection.find({'name': {'$lt': 4}})
    # Modify the query before iterating
    cursor.sort('name', -1).skip(1).limit(2)
    async for document in cursor:
        pprint.pprint(document)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_find())

 

六、統計

async def do_count():
    n = await db.test_collection.count_documents({})
    print('%s documents in collection' % n)
    n = await db.test_collection.count_documents({'name': {'$gt': 1000}})
    print('%s documents where i > 1000' % n)

loop = asyncio.get_event_loop()
loop.run_until_complete(do_count())

 

七、替換

async def do_replace():
    coll = db.test_collection
    old_document = await coll.find_one({'name': 'zone'})
    print('found document: %s' % pprint.pformat(old_document))
    _id = old_document['_id']
    result = await coll.replace_one({'_id': _id}, {'sex': 'hanson boy'})
    print('replaced %s document' % result.modified_count)
    new_document = await coll.find_one({'_id': _id})
    print('document is now %s' % pprint.pformat(new_document))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_replace())

 

八、更新指定字段,不會影響到其他內容

async def do_update():
    coll = db.test_collection
    result = await coll.update_one({'name': 0}, {'$set': {'sex': 'girl'}})
    print('更新條數: %s ' % result.modified_count)
    new_document = await coll.find_one({'name': 0})
    print('更新結果為: %s' % pprint.pformat(new_document))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_update())

 

九、刪除置頂記錄

async def do_delete_many():
    coll = db.test_collection
    n = await coll.count_documents({})
    print('刪除前有 %s 條數據' % n)
    result = await db.test_collection.delete_many({'name': {'$gte': 10}})
    print('刪除后 %s ' % (await coll.count_documents({})))

loop = asyncio.get_event_loop()
loop.run_until_complete(do_delete_many())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM