赵走x博客
网站访问量:151519
首页
书籍
软件
工具
古诗词
搜索
登录
1、motor使用入门
1、motor使用入门
资源编号:76448
Sanic
Python
热度:114
来源:https://motor.readthedocs.io/en/stable/tutorial-asyncio.html
``` python3 -m pip install motor ``` 与PyMongo一样,Motor表示具有4级对象层次结构的数据: * AsyncIOMotorClient 代表一个mongod进程,或一个集群。您显式创建了这些客户端对象之一,将其连接到一个正在运行的mongod上,并将其用于应用程序的整个生命周期。 * AsyncIOMotorDatabase:每个mongod都有一组数据库(磁盘上不同的数据文件集)。您可以从客户端获取对数据库的引用。 * AsyncIOMotorCollection:数据库具有一组集合,其中包含文档;您可以从数据库中获得对集合的引用。 * AsyncIOMotorCursor:find()在AsyncIOMotorCollection获取时执行AsyncIOMotorCursor,该代表与查询匹配的文档集。 # 1、创建一个客户端 通常,AsyncIOMotorClient在应用程序启动时创建一个的实例。 ``` >>> import motor.motor_asyncio >>> client = motor.motor_asyncio.AsyncIOMotorClient() ``` 这将连接到mongod默认主机和端口上的侦听。您可以指定主机和端口,例如: ``` >>> client = motor.motor_asyncio.AsyncIOMotorClient('localhost', 27017) ``` Motor还支持连接URI: ``` >>> client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') ``` 连接到副本集,例如: ``` >>> client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://host1,host2/?replicaSet=my-replicaset-name') ``` # 2、获取数据库 MongoDB的单个实例可以支持多个独立的 数据库。从开放式客户端,您可以使用点符号或方括号符号获取对特定数据库的引用: ``` >>> db = client.test_database >>> db = client['test_database'] ``` 创建对数据库的引用不会产生I / O,并且不需要 await表达式。 # 3、获取集合 一个集合 是一组存储在MongoDB中的文档,并且可以作为大致在关系数据库中的表的等价被认为。在Motor中获取集合与获取数据库的工作原理相同: ``` >>> collection = db.test_collection >>> collection = db['test_collection'] ``` 就像获取对数据库的引用一样,对集合的引用也不需要I / O,也不需要await表达式。 # 4、插入文档 与PyMongo中一样,Motor用Python字典表示MongoDB文档。要存储在MongoDB中的文档,调用insert_one()在 await表达式: ``` >>> async def do_insert(): ... document = {'key': 'value'} ... result = await db.test_collection.insert_one(document) ... print('result %s' % repr(result.inserted_id)) ... >>> >>> import asyncio >>> 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)]) ... print('inserted %d docs' % (len(result.inserted_ids),)) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_insert()) inserted 2000 docs ``` # 5、使用find_one获取单个文档 使用find_one()得到匹配查询的第一个文档。例如,要获取键“ i”的值小于1的文档: ``` >>> async def do_find_one(): ... document = await db.test_collection.find_one({'i': {'$lt': 1}}) ... pprint.pprint(document) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_find_one()) {'_id': ObjectId('...'), 'i': 0} ``` 结果是与我们先前插入的字典匹配的字典。 >注意 返回的文档包含"_id",会在插入时自动添加。 # 6、查询多个文档 ``` >>> async def do_find(): ... cursor = db.test_collection.find({'i': {'$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()) {'_id': ObjectId('...'), 'i': 0} {'_id': ObjectId('...'), 'i': 1} {'_id': ObjectId('...'), 'i': 2} {'_id': ObjectId('...'), 'i': 3} {'_id': ObjectId('...'), 'i': 4} ``` >A length argument is required when you call to_list to prevent Motor from buffering an unlimited number of documents. #### async for 您可以一次循环处理一个文档:async for ``` >>> async def do_find(): ... c = db.test_collection ... async for document in c.find({'i': {'$lt': 2}}): ... pprint.pprint(document) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_find()) {'_id': ObjectId('...'), 'i': 0} {'_id': ObjectId('...'), 'i': 1} ``` 您可以在开始迭代之前对查询应用排序,限制或跳过: ``` >>> async def do_find(): ... cursor = db.test_collection.find({'i': {'$lt': 4}}) ... # Modify the query before iterating ... cursor.sort('i', -1).skip(1).limit(2) ... async for document in cursor: ... pprint.pprint(document) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_find()) {'_id': ObjectId('...'), 'i': 2} {'_id': ObjectId('...'), 'i': 1} ``` >The cursor does not actually retrieve each document from the server individually; it gets documents efficiently in large batches. # 7、查询数量 使用count_documents()确定的集合,或与查询匹配的文档数量中的档案数量: ``` >>> async def do_count(): ... n = await db.test_collection.count_documents({}) ... print('%s documents in collection' % n) ... n = await db.test_collection.count_documents({'i': {'$gt': 1000}}) ... print('%s documents where i > 1000' % n) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_count()) 2000 documents in collection 999 documents where i > 1000 ``` # 8、更新文档 replace_one()更改文档。它需要两个参数:一个用于指定要替换的文档的查询和一个替换文档。查询遵循与find()或 相同的语法find_one()。替换文档: ``` >>> async def do_replace(): ... coll = db.test_collection ... old_document = await coll.find_one({'i': 50}) ... print('found document: %s' % pprint.pformat(old_document)) ... _id = old_document['_id'] ... result = await coll.replace_one({'_id': _id}, {'key': 'value'}) ... 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()) found document: {'_id': ObjectId('...'), 'i': 50} replaced 1 document document is now {'_id': ObjectId('...'), 'key': 'value'} ``` 您可以看到replace_one()用旧文档替换了旧文档中的所有_id内容。 update_one()与MongoDB的修饰符运算符一起使用可更新文档的一部分,其余部分保持不变。 我们将找到“ i”为51的文档,并使用$set 运算符将“键”设置为“值”: ``` >>> async def do_update(): ... coll = db.test_collection ... result = await coll.update_one({'i': 51}, {'$set': {'key': 'value'}}) ... print('updated %s document' % result.modified_count) ... new_document = await coll.find_one({'i': 51}) ... print('document is now %s' % pprint.pformat(new_document)) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_update()) updated 1 document document is now {'_id': ObjectId('...'), 'i': 51, 'key': 'value'} ``` “键”设置为“值”,而“ i”仍为51。 update_one()仅影响找到的第一个文档,您可以使用以下命令更新所有文档update_many(): ``` await coll.update_many({'i': {'$gt': 100}}, {'$set': {'key': 'value'}}) ``` # 9、删除文档 delete_many()使用与相同的语法进行查询 find()。 delete_many()立即删除所有匹配的文档。 ``` >>> async def do_delete_many(): ... coll = db.test_collection ... n = await coll.count_documents({}) ... print('%s documents before calling delete_many()' % n) ... result = await db.test_collection.delete_many({'i': {'$gte': 1000}}) ... print('%s documents after' % (await coll.count_documents({}))) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(do_delete_many()) 2000 documents before calling delete_many() 1000 documents after ``` # 10、命令 MongoDB上的所有操作都在内部作为命令实现。使用以下command()方法 运行它们AsyncIOMotorDatabase: ``` .. doctest:: after-inserting-2000-docs ``` ``` >>> from bson import SON >>> async def use_distinct_command(): ... response = await db.command(SON([("distinct", "test_collection"), ... ("key", "i")])) ... >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(use_distinct_command()) ``` 由于命令参数的顺序很重要,因此请勿使用Python dict传递命令的参数。相反,要使用的习惯bson.SON,从bson附带PyMongo模块。 许多命令具有特殊的帮助程序方法,例如 create_collection()或 aggregate(),但这只是基本command()方法之上的便利。