安装
python3 -m pip install motor
创建客户端
指定主机和端口号
import motor.motor_asyncio
client = motor.motor_asyncio.AsyncIOMotorClient('localhost', 27017)
使用用户名和密码
motor.motor_asyncio.AsyncIOMotorClient('mongodb://root:123456@localhost:27017')
获取数据库
MongoDB的单个实例可以支持多个独立的数据库。在开放式客户端中,您可以使用点表示法或括号表示法来获取对特定数据库的引用:
db = client.test_database
db = client['test_database']
创建对数据库的引用不会执行I / O,也不需要 await 表达式。
获取集合
一个集合是一组存储在MongoDB中的文档,并且可以被认为是大致在关系数据库中的表的当量。获取Motor中的集合与获取数据库的工作方式相同:
collection = db.test_collection
collection = db['test_collection']
就像获取对数据库的引用一样,获取对集合的引用不会产生I / O并且不需要 await 表达式。
插入文档(insert_one)
与pymongo一样,Motor使用Python字典表示MongoDB文档。要存储在MongoDB中的文档,在 await 表达式中调用 insert_one() :
async def do_insert():
document = {'key': 'value'}
result = await db.test_collection.insert_one(document) # insert_one只能插入一条数据
print('result %s' % repr(result.inserted_id))
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())
# result ObjectId('...')
批量插入文档(insert_many)
async def do_insert():
result = await db.test_collection.insert_many(
[{'i': i} for i in range(2000)]) # insert_many可以插入一条或多条数据ÿ