Asynchronous Python library for MongoDB - Motor
Before using this third-party library, familiarize yourself with Python asyncio.
- Installation
python3 -m pip install motor
# Motor version requirements:
python>=3.5
pymongo>=3.12
- Create a client
client = motor.motor_asyncio.AsyncIOMotorClient('localhost', 27017)
or
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://{user}:{password}@{host}:{port}', maxPoolSize=50)
- Access the data base
db = client.test_database
or
db = client['test_database']
# This process does not involve I/O operations and does not require await
- Access the collecsion
collection = db.test_collection
or
collection = db['test_collection']
# Similarly, no I/O operations involved
- Insert a single document
doc = {'name': 'xxx'}
result = await db.test_collection.insert_one(doc)
- Insert multiple documents
doc_list = [{'name': 'xxx'}, {'name': 'yyy'}, ...]
result = await db.test_collection.insert_many(doc_list)
- Find a single document
doc = await db.test_collection.find_one({'name': 'xxx'})
- Query multiple documenst
# To query multiple documents, use the find() method. This method does not involve I/O and does not require await. It creates an AsyncIOMotorCursor instance, which is an asynchronous iterator that needs to be accessed via async for.
# Basic usage
cursor = db.test_collection.find({'age': {'$lt': 10}}).sort('age', -1).skip(2).limit(2)
async for doc in cursor:
...
- Count documents
n = await db.test_collection.count_documents({'age': {'$lt': 10}})
- Update documents
# Replace a single document entirely
result = await db.test_collection.replace_one({filter}, {})
# Partially update a single document
result = await db.test_collection.update_one({filter}, {'$set': {}})
- Delete documents
res = await db.test_collection.delete_many({filter})
- Additional details
https://motor.readthedocs.io/en/stable/api-tornado/motor_client.html