AsyncIOMotorClient – Connection to MongoDB

class motor.motor_asyncio.AsyncIOMotorClient(*args, **kwargs)

Create a new connection to a single MongoDB instance at host:port.

Takes the same constructor arguments as MongoClient, as well as:

Parameters:
  • io_loop (optional): Special event loop instance to use instead of default.

client[db_name] || client.db_name

Get the db_name AsyncIOMotorDatabase on AsyncIOMotorClient client.

Raises InvalidName if an invalid database name is used.

coroutine bulk_write(models: Sequence[_WriteOp[_DocumentType]], session: ClientSession | None = None, ordered: bool = True, verbose_results: bool = False, bypass_document_validation: bool | None = None, comment: Any | None = None, let: Mapping | None = None, write_concern: WriteConcern | None = None) ClientBulkWriteResult

Send a batch of write operations, potentially across multiple namespaces, to the server.

Requests are passed as a list of write operation instances ( InsertOne, UpdateOne, UpdateMany, ReplaceOne, DeleteOne, or DeleteMany).

>>> for doc in db.test.find({}):
...     print(doc)
...
{'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
{'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
...
>>> for doc in db.coll.find({}):
...     print(doc)
...
{'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
...
>>> # DeleteMany, UpdateOne, and UpdateMany are also available.
>>> from pymongo import InsertOne, DeleteOne, ReplaceOne
>>> models = [InsertOne(namespace="db.test", document={'y': 1}),
...           DeleteOne(namespace="db.test", filter={'x': 1}),
...           InsertOne(namespace="db.coll", document={'y': 2}),
...           ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)]
>>> result = client.bulk_write(models=models)
>>> result.inserted_count
2
>>> result.deleted_count
1
>>> result.modified_count
0
>>> result.upserted_count
1
>>> for doc in db.test.find({}):
...     print(doc)
...
{'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
{'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
{'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
...
>>> for doc in db.coll.find({}):
...     print(doc)
...
{'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
{'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')}
Parameters:
  • models – A list of write operation instances.

  • session – (optional) An instance of ClientSession.

  • ordered – If True (the default), requests will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. If False, requests will be still performed on the server serially, in the order provided, but all operations will be attempted even if any errors occur.

  • verbose_results – If True, detailed results for each successful operation will be included in the returned ClientBulkWriteResult. Default is False.

  • bypass_document_validation – (optional) If True, allows the write to opt-out of document level validation. Default is False.

  • comment – (optional) A user-provided comment to attach to this command.

  • let – (optional) Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. “$$var”).

  • write_concern – (optional) The write concern to use for this bulk write.

Returns:

An instance of ClientBulkWriteResult.

Note

requires MongoDB server version 8.0+.

coroutine drop_database(name_or_database: str | Database[_DocumentTypeArg], session: ClientSession | None = None, comment: Any | None = None) None

Drop a database.

Raises TypeError if name_or_database is not an instance of str or Database.

Parameters:
  • name_or_database – the name of a database to drop, or a Database instance representing the database to drop

  • session – a ClientSession.

  • comment – A user-provided comment to attach to this command.

Note

The write_concern of this client is automatically applied to this operation.

get_database(name: str | None = None, codec_options: CodecOptions[_DocumentTypeArg] | None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) database.Database[_DocumentType]

Get a MotorDatabase with the given name and options.

Useful for creating a MotorDatabase with different codec options, read preference, and/or write concern from this MotorClient.

>>> from pymongo import ReadPreference
>>> client.read_preference == ReadPreference.PRIMARY
True
>>> db1 = client.test
>>> db1.read_preference == ReadPreference.PRIMARY
True
>>> db2 = client.get_database(
...     'test', read_preference=ReadPreference.SECONDARY)
>>> db2.read_preference == ReadPreference.SECONDARY
True
Parameters:
  • name: The name of the database - a string.

  • codec_options (optional): An instance of CodecOptions. If None (the default) the codec_options of this MotorClient is used.

  • read_preference (optional): The read preference to use. If None (the default) the read_preference of this MotorClient is used. See read_preferences for options.

  • write_concern (optional): An instance of WriteConcern. If None (the default) the write_concern of this MotorClient is used.

get_default_database(default: str | None = None, codec_options: CodecOptions[_DocumentTypeArg] | None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) database.Database[_DocumentType]

Get the database named in the MongoDB connection URI.

>>> uri = 'mongodb://host/my_database'
>>> client = MotorClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
>>> db = client.get_default_database('fallback_db_name')
>>> assert db.name == 'my_database'
>>> uri_without_database = 'mongodb://host/'
>>> client = MotorClient(uri_without_database)
>>> db = client.get_default_database('fallback_db_name')
>>> assert db.name == 'fallback_db_name'

Useful in scripts where you want to choose which database to use based only on the URI in a configuration file.

Parameters:
  • default (optional): the database name to use if no database name was provided in the URI.

  • codec_options (optional): An instance of CodecOptions. If None (the default) the codec_options of this MotorClient is used.

  • read_preference (optional): The read preference to use. If None (the default) the read_preference of this MotorClient is used. See read_preferences for options.

  • write_concern (optional): An instance of WriteConcern. If None (the default) the write_concern of this MotorClient is used.

  • read_concern (optional): An instance of ReadConcern. If None (the default) the read_concern of this MotorClient is used.

  • comment (optional): A user-provided comment to attach to this command.

Changed in version 3.0: Added comment parameter.

Added in version 2.1: Revived this method. Added the default, codec_options, read_preference, write_concern and read_concern parameters.

Changed in version 2.0: Removed this method.

coroutine list_database_names(session: ClientSession | None = None, comment: Any | None = None) list[str]

Get a list of the names of all databases on the connected server.

Parameters:
  • session – a ClientSession.

  • comment – A user-provided comment to attach to this command.

coroutine async list_databases(session: ClientSession | None = None, comment: Any | None = None, **kwargs: Any) CommandCursor[dict[str, Any]]

Get a cursor over the databases of the connected server.

Parameters:
  • session – a ClientSession.

  • comment – A user-provided comment to attach to this command.

  • kwargs – Optional parameters of the listDatabases command can be passed as keyword arguments to this method. The supported options differ by server version.

Returns:

An instance of CommandCursor.

coroutine server_info(session: ClientSession | None = None) dict[str, Any]

Get information about the MongoDB server we’re connected to.

Parameters:

session – a ClientSession.

coroutine async start_session(causal_consistency: bool | None = None, default_transaction_options: TransactionOptions | None = None, snapshot: bool | None = False) ClientSession

Start a logical session.

This method takes the same parameters as PyMongo’s SessionOptions. See the client_session module for details.

This session is created uninitialized, use it in an await expression to initialize it, or an async with statement.

async def coro():
    collection = client.db.collection

    # End the session after using it.
    s = await client.start_session()
    await s.end_session()

    # Or, use an "async with" statement to end the session
    # automatically.
    async with await client.start_session() as s:
        doc = {"_id": ObjectId(), "x": 1}
        await collection.insert_one(doc, session=s)

        secondary = collection.with_options(read_preference=ReadPreference.SECONDARY)

        # Sessions are causally consistent by default, so we can read
        # the doc we just inserted, even reading from a secondary.
        async for doc in secondary.find(session=s):
            print(doc)

    # Run a multi-document transaction:
    async with await client.start_session() as s:
        # Note, start_transaction doesn't require "await".
        async with s.start_transaction():
            await collection.delete_one({"x": 1}, session=s)
            await collection.insert_one({"x": 2}, session=s)

        # Exiting the "with s.start_transaction()" block while throwing an
        # exception automatically aborts the transaction, exiting the block
        # normally automatically commits it.

        # You can run additional transactions in the same session, so long as
        # you run them one at a time.
        async with s.start_transaction():
            await collection.insert_one({"x": 3}, session=s)
            await collection.insert_many(
                {"x": {"$gte": 2}}, {"$inc": {"x": 1}}, session=s
            )

Requires MongoDB 3.6. Do not use the same session for multiple operations concurrently. A MotorClientSession may only be used with the MotorClient that started it.

Returns:

An instance of MotorClientSession.

Changed in version 2.0: Returns a MotorClientSession. Before, this method returned a PyMongo ClientSession.

Added in version 1.2.

watch(pipeline=None, full_document=None, resume_after=None, max_await_time_ms=None, batch_size=None, collation=None, start_at_operation_time=None, session=None, start_after=None, comment=None, full_document_before_change=None, show_expanded_events=None)

Watch changes on this cluster.

Returns a MotorChangeStream cursor which iterates over changes on all databases in this cluster. Introduced in MongoDB 4.0.

See the documentation for MotorCollection.watch() for more details and examples.

Parameters:
  • pipeline (optional): A list of aggregation pipeline stages to append to an initial $changeStream stage. Not all pipeline stages are valid after a $changeStream stage, see the MongoDB documentation on change streams for the supported stages.

  • full_document (optional): The fullDocument option to pass to the $changeStream stage. Allowed values: ‘updateLookup’. When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.

  • resume_after (optional): A resume token. If provided, the change stream will start returning changes that occur directly after the operation specified in the resume token. A resume token is the _id value of a change document.

  • max_await_time_ms (optional): The maximum time in milliseconds for the server to wait for changes before responding to a getMore operation.

  • batch_size (optional): The maximum number of documents to return per batch.

  • collation (optional): The Collation to use for the aggregation.

  • start_at_operation_time (optional): If provided, the resulting change stream will only return changes that occurred at or after the specified Timestamp. Requires MongoDB >= 4.0.

  • session (optional): a ClientSession.

  • start_after (optional): The same as resume_after except that start_after can resume notifications after an invalidate event. This option and resume_after are mutually exclusive.

  • comment (optional): A user-provided comment to attach to this command.

  • full_document_before_change: Allowed values: whenAvailable and required. Change events may now result in a fullDocumentBeforeChange response field.

  • show_expanded_events (optional): Include expanded events such as DDL events like dropIndexes.

Returns:

A MotorChangeStream.

Changed in version 3.2: Added show_expanded_events parameter.

Changed in version 3.1: Added full_document_before_change parameter.

Changed in version 3.0: Added comment parameter.

Changed in version 2.1: Added the start_after parameter.

Added in version 2.0.

See also

The MongoDB documentation on

changeStreams

property HOST

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

property PORT

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

property address

(host, port) of the current standalone, primary, or mongos, or None.

Accessing address raises InvalidOperation if the client is load-balancing among mongoses, since there is no single address. Use nodes instead.

If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

Added in version 3.0.

property arbiters

Arbiters in the replica set.

A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the replicaSet option.

property close

Cleanup client resources and disconnect from MongoDB.

End all server sessions created by this client by sending one or more endSessions commands.

Close all sockets in the connection pools and stop the monitor threads.

Changed in version 4.0: Once closed, the client cannot be used again and any attempt will raise InvalidOperation.

Changed in version 3.6: End all server sessions created by this client.

property codec_options

Read only access to the CodecOptions of this instance.

property is_mongos

If this client is connected to mongos. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

property is_primary

If this client is connected to a server that can accept writes.

True if the current server is a standalone, mongos, or the primary of a replica set. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

property nodes

Set of all currently connected servers.

Warning

When connected to a replica set the value of nodes can change over time as MongoClient’s view of the replica set changes. nodes can also be an empty set when MongoClient is first instantiated and hasn’t yet connected to any servers, or a network partition causes it to lose connection to all servers.

property options

The configuration options for this client.

Returns:

An instance of ClientOptions.

Added in version 4.0.

property primary

The (host, port) of the current primary of the replica set.

Returns None if this client is not connected to a replica set, there is no primary, or this client was created without the replicaSet option.

Added in version 3.0: MongoClient gained this property in version 3.0.

property read_concern

Read only access to the ReadConcern of this instance.

Added in version 3.2.

property read_preference

Read only access to the read preference of this instance.

Changed in version 3.0: The read_preference attribute is now read only.

property secondaries

The secondary members known to this client.

A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the replicaSet option.

Added in version 3.0: MongoClient gained this property in version 3.0.

property topology_description

The description of the connected MongoDB deployment.

>>> client.topology_description
<TopologyDescription id: 605a7b04e76489833a7c6113, topology_type: ReplicaSetWithPrimary, servers: [<ServerDescription ('localhost', 27017) server_type: RSPrimary, rtt: 0.0007973677999995488>, <ServerDescription ('localhost', 27018) server_type: RSSecondary, rtt: 0.0005540556000003249>, <ServerDescription ('localhost', 27019) server_type: RSSecondary, rtt: 0.0010367483999999649>]>
>>> client.topology_description.topology_type_name
'ReplicaSetWithPrimary'

Note that the description is periodically updated in the background but the returned object itself is immutable. Access this property again to get a more recent TopologyDescription.

Returns:

An instance of TopologyDescription.

Added in version 4.0.

property write_concern

Read only access to the WriteConcern of this instance.

Changed in version 3.0: The write_concern attribute is now read only.