Motor同时支持使用asyncio(Python3.4以上标准库)作为异步模型,使用起来十分方便。
我们来测试一下效率,使用传统pymongo来进行批量读写 mongo_test.py:
host = '127.0.0.1'
port = 27017
database = 'LiePin'
import time
start = time.clock()
from pymongo import MongoClient
connection = MongoClient(
host,
port
)
db = connection[database]
for doc in db.LiePin_Analysis1.find({}, ['_id', 'JobTitle', 'is_end']):
db.LiePin_Analysis1.update_one({'_id': doc.get('_id')}, {
'$set': {
'is_end': 1
}
})
elapsed = (time.clock() - start)
print("Time used:",elapsed)
运行一下,发现用了4秒左右
再使用motor以异步的形式来编写脚本 motor_test.py
host = '127.0.0.1'
port = 27017
database = 'LiePin'
import time
start = time.clock()
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
connection = AsyncIOMotorClient(
host,
port
)
db = connection[database]
async def run():
async for doc in db.LiePin_Analysis1.find({}, ['_id', 'JobTitle', 'is_end']):
db.LiePin_Analysis1.update_one({'_id': doc.get('_id')}, {'$set': {'is_end':0}})
asyncio.get_event_loop().run_until_complete(run())
elapsed = (time.clock() - start)
print("Time used:",elapsed)
仅仅1秒左右就完成了任务
效率由此可见一斑。