Migrate from Motor 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 migrate an application from Motor to the PyMongo Async driver.
Migrate From Motor
The PyMongo Async driver functions similarly to the Motor library, but allows
for improved latency and throughput due to directly using Python Asyncio instead
of delegating work to a thread pool. In most cases, you can directly migrate
existing Motor applications to PyMongo Async by using AsyncMongoClient
in
place of MotorClient
, and changing the application's import statements to
import from pymongo
.
The following example shows the difference in imports to use a client for read and write operations in Motor compared to PyMongo Async:
# Motor client import from motor.motor_asyncio import AsyncIOMotorClient # PyMongo Async client import from pymongo import AsyncMongoClient
To see a list of the asynchronous methods available in the PyMongo Async driver, see the Asynchronous Methods section in the PyMongo to PyMongo Async guide.
The following section shows the method signature changes that you must implement in your application when migrating from Motor to the PyMongo Async driver.
Method Signature Changes
The following Motor method signatures behave differently in the PyMongo Async driver:
AsyncMongoClient.__init__()
does not accept anio_loop
parameter.AsyncCursor.each()
does not exist in the PyMongo Async driver.MotorGridOut.stream_to_handler()
does not exist in the PyMongo Async driver.AsyncCursor.to_list(0)
is not valid in the PyMongo Async driver. Useto_list(None)
instead.MongoClient
is thread safe and can be used by many threads, however, anAsyncMongoClient
is not thread safe and should only be used by a single event loop.
Additional Information
To learn more about asynchronous Python, see the Python Asyncio documentation.