Switch from PyMongo to PyMongo Async
Important
The PyMongo Async driver is experimental and should not be used in production environments. Classes, methods, and behaviors described in this guide might change prior to the full release. If you encounter any issues with PyMongo Async, you can learn how to report them on the Issues & Help page.
Overview
The PyMongo Async driver is a unification of PyMongo and the Motor library. In this guide, you can identify the changes you must make to switch from PyMongo to PyMongo Async.
Switch From PyMongo
The PyMongo Async driver behaves similarly to PyMongo, but all methods that perform network operations are coroutines and must be awaited. To switch from PyMongo to PyMongo Async, you must update your code in the following ways:
Replace all uses of
MongoClient
withAsyncMongoClient
.Add the
await
keyword to all asynchronous method calls.If you call an asynchronous method inside of a function, mark the function as
async
.
The following sections describe how to implement the asynchronous API.
Asynchronous Methods
The following tables list the asynchronous methods that are available in the
PyMongo Async driver. To call these methods, you must await
them and call them
inside an async
function.
Client Methods
Method | Example | |||
---|---|---|---|---|
AsyncMongoClient() |
| |||
watch() |
| |||
server_info() |
| |||
list_databases() |
| |||
list_database_names() |
| |||
drop_database() |
|
Database Methods
Method | Example | ||
---|---|---|---|
watch() |
| ||
create_collection() |
| ||
aggregate() |
| ||
command() |
| ||
cursor_command() |
| ||
list_collections() |
| ||
list_collection_names() |
| ||
drop_collection() |
| ||
validate_collection() |
| ||
dereference() |
|
Collection Methods
Method | Example | ||
---|---|---|---|
watch() |
| ||
insert_one() |
| ||
insert_many() |
| ||
replace_one() |
| ||
update_one() |
| ||
update_many() |
| ||
drop() |
| ||
delete_one() |
| ||
delete_many() |
| ||
find_one() |
| ||
estimated_document_count() |
| ||
count_documents() |
| ||
create_index() |
| ||
create_indexes() |
| ||
drop_index() |
| ||
drop_indexes() |
| ||
list_indexes() |
| ||
index_information() |
| ||
list_search_indexes() |
| ||
create_search_index() |
| ||
create_search_indexes() |
| ||
drop_search_index() |
| ||
update_search_index() |
| ||
options() |
| ||
aggregate() |
| ||
aggregate_raw_batches() |
| ||
rename() |
| ||
distinct() |
| ||
find_one_and_delete() |
| ||
find_one_and_replace() |
| ||
find_one_and_update() |
|
Additional Information
To learn more about asynchronous Python, see the Python Asyncio documentation.