MotorDatabase¶
Warning
Motor will be deprecated on May 14th, 2026, one year after the production release of the PyMongo Async driver. Critical bug fixes will be made until May 14th, 2027. We strongly recommend that Motor users migrate to the PyMongo Async driver while Motor is still supported. To learn more, see the migration guide.
- class motor.motor_tornado.MotorDatabase(client, name, **kwargs)¶
- db[collection_name] || db.collection_name
Get the collection_name
MotorCollectionofMotorDatabasedb.Raises
InvalidNameif an invalid collection name is used.
- aggregate(pipeline, *args, **kwargs)¶
Execute an aggregation pipeline on this database.
Introduced in MongoDB 3.6.
The aggregation can be run on a secondary if the client is connected to a replica set and its
read_preferenceis notPRIMARY. Theaggregate()method obeys theread_preferenceof thisMotorDatabase, except when$outor$mergeare used, in which casePRIMARYis used.All optional aggregate command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:
allowDiskUse (bool): Enables writing to temporary files. When set to True, aggregation stages can write data to the _tmp subdirectory of the –dbpath directory. The default is False.
maxTimeMS (int): The maximum amount of time to allow the operation to run in milliseconds.
batchSize (int): The maximum number of documents to return per batch. Ignored if the connected mongod or mongos does not support returning aggregate results using a cursor.
collation (optional): An instance of
Collation.let (dict): A dict 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"). This option is only supported on MongoDB >= 5.0.
Returns a
MotorCommandCursorthat can be iterated like a cursor fromfind():async def f(): # Lists all operations currently running on the server. pipeline = [{"$currentOp": {}}] async for operation in client.admin.aggregate(pipeline): print(operation)
Note
This method does not support the ‘explain’ option. Please use
MotorDatabase.command()instead.Note
The
MotorDatabase.write_concernof this database is automatically applied to this operation.Added in version 2.1.
- coroutine command(command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode | None = None, codec_options: bson.codec_options.CodecOptions[_CodecDocumentType] | None = None, session: ClientSession | None = None, comment: Any | None = None, **kwargs: Any) dict[str, Any] | _CodecDocumentType¶
Issue a MongoDB command.
Send command
commandto the database and return the response. Ifcommandis a string then the command{command: value}will be sent. Otherwise,commandmust be adictand will be sent as-is.Additional keyword arguments are added to the final command document before it is sent.
For example, a command like
{buildinfo: 1}can be sent using:result = await db.command("buildinfo")
For a command where the value matters, like
{count: collection_name}we can do:result = await db.command("count", collection_name)
For commands that take additional arguments we can use kwargs. So
{count: collection_name, query: query}becomes:result = await db.command("count", collection_name, query=query)
- Parameters:
command: document representing the command to be issued, or the name of the command (for simple commands only).
value (optional): value to use for the command verb when command is passed as a string
check (optional): check the response for errors, raising
OperationFailureif there are anyallowable_errors: if check is
True, error messages in this list will be ignored by error-checkingread_preference: The read preference for this operation. See
read_preferencesfor options.session (optional): a
ClientSession, created withstart_session().comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): additional keyword arguments will be added to the command document before it is sent
Changed in version 3.0: Added comment parameter.
Changed in version 1.2: Added session parameter.
- coroutine async create_collection(name: str, codec_options: CodecOptions[_DocumentTypeArg] | None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None, session: ClientSession | None = None, check_exists: bool | None = True, **kwargs: Any) Collection[_DocumentType]¶
Create a new
Collectionin this database.Normally collection creation is automatic. This method should only be used to specify options on creation.
CollectionInvalidwill be raised if the collection already exists.- Parameters:
name – the name of the collection to create
codec_options – An instance of
CodecOptions. IfNone(the default) thecodec_optionsof thisDatabaseis used.read_preference – The read preference to use. If
None(the default) theread_preferenceof thisDatabaseis used.write_concern – An instance of
WriteConcern. IfNone(the default) thewrite_concernof thisDatabaseis used.read_concern – An instance of
ReadConcern. IfNone(the default) theread_concernof thisDatabaseis used.collation – An instance of
Collation.session – a
ClientSession.check_exists – if True (the default), send a listCollections command to check if the collection already exists before creation.
kwargs – additional keyword arguments will be passed as options for the create collection command
All optional create collection command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:
size(int): desired initial size for the collection (in bytes). For capped collections this size is the max size of the collection.capped(bool): if True, this is a capped collectionmax(int): maximum number of objects if capped (optional)timeseries(dict): a document specifying configuration options for timeseries collectionsexpireAfterSeconds(int): the number of seconds after which a document in a timeseries collection expiresvalidator(dict): a document specifying validation rules or expressions for the collectionvalidationLevel(str): how strictly to apply the validation rules to existing documents during an update. The default level is “strict”validationAction(str): whether to “error” on invalid documents (the default) or just “warn” about the violations but allow invalid documents to be insertedindexOptionDefaults(dict): a document specifying a default configuration for indexes when creating a collectionviewOn(str): the name of the source collection or view from which to create the viewpipeline(list): a list of aggregation pipeline stagescomment(str): a user-provided comment to attach to this command. This option is only supported on MongoDB >= 4.4.encryptedFields(dict): (BETA) Document that describes the encrypted fields for Queryable Encryption. For example:{ "escCollection": "enxcol_.encryptedCollection.esc", "ecocCollection": "enxcol_.encryptedCollection.ecoc", "fields": [ { "path": "firstName", "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), "bsonType": "string", "queries": {"queryType": "equality"} }, { "path": "ssn", "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), "bsonType": "string" } ] }
clusteredIndex(dict): Document that specifies the clustered index configuration. It must have the following form:{ // key pattern must be {_id: 1} key: <key pattern>, // required unique: <bool>, // required, must be `true` name: <string>, // optional, otherwise automatically generated v: <int>, // optional, must be `2` if provided }changeStreamPreAndPostImages(dict): a document with a boolean fieldenabledfor enabling pre- and post-images.
- async cursor_command(command, value=1, read_preference=None, codec_options=None, session=None, comment=None, max_await_time_ms=None, **kwargs)¶
Issue a MongoDB command and parse the response as a cursor.
If the response from the server does not include a cursor field, an error will be thrown.
Otherwise, behaves identically to issuing a normal MongoDB command.
- Parameters:
command: document representing the command to be issued, or the name of the command (for simple commands only).
Note
the order of keys in the command document is significant (the “verb” must come first), so commands which require multiple keys (e.g. findandmodify) should use an instance of
SONor a string and kwargs instead of a Python dict.value (optional): value to use for the command verb when command is passed as a string
read_preference (optional): The read preference for this operation. See
read_preferencesfor options. If the provided session is in a transaction, defaults to the read preference configured for the transaction. Otherwise, defaults toPRIMARY.codec_options: A
CodecOptionsinstance.session (optional): A
MotorClientSession.comment (optional): A user-provided comment to attach to future getMores for this command.
max_await_time_ms (optional): The number of ms to wait for more data on future getMores for this command.
**kwargs (optional): additional keyword arguments will be added to the command document before it is sent
Note
command()does not obey this Database’sread_preferenceorcodec_options. You must use theread_preferenceandcodec_optionsparameters instead.Note
command()does not apply any custom TypeDecoders when decoding the command response.Note
If this client has been configured to use MongoDB Stable API (see MongoDB Stable API), then
command()will automatically add API versioning options to the given command. Explicitly adding API versioning options in the command and declaring an API version on the client is not supported.See also
The MongoDB documentation on commands.
- coroutine dereference(dbref: DBRef, session: ClientSession | None = None, comment: Any | None = None, **kwargs: Any) _DocumentType | None¶
Dereference a
DBRef, getting the document it points to.Raises
TypeErrorif dbref is not an instance ofDBRef. Returns a document, orNoneif the reference does not point to a valid document. RaisesValueErrorif dbref has a database specified that is different from the current database.- Parameters:
dbref – the reference
session – a
ClientSession.comment – A user-provided comment to attach to this command.
kwargs – any additional keyword arguments are the same as the arguments to
find().
- coroutine drop_collection(name_or_collection: str | Collection[_DocumentTypeArg], session: ClientSession | None = None, comment: Any | None = None, encrypted_fields: Mapping[str, Any] | None = None) dict[str, Any]¶
Drop a collection.
- Parameters:
name_or_collection – the name of a collection to drop or the collection object itself
session – a
ClientSession.comment – A user-provided comment to attach to this command.
encrypted_fields –
(BETA) Document that describes the encrypted fields for Queryable Encryption. For example:
{ "escCollection": "enxcol_.encryptedCollection.esc", "ecocCollection": "enxcol_.encryptedCollection.ecoc", "fields": [ { "path": "firstName", "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')), "bsonType": "string", "queries": {"queryType": "equality"} }, { "path": "ssn", "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')), "bsonType": "string" } ] }
Note
The
write_concernof this database is automatically applied to this operation.
- get_collection(name: str, codec_options: CodecOptions[_DocumentTypeArg] | None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) Collection[_DocumentType]¶
Get a
Collectionwith the given name and options.Useful for creating a
Collectionwith different codec options, read preference, and/or write concern from thisDatabase.>>> db.read_preference Primary() >>> coll1 = db.test >>> coll1.read_preference Primary() >>> from pymongo import ReadPreference >>> coll2 = db.get_collection( ... 'test', read_preference=ReadPreference.SECONDARY) >>> coll2.read_preference Secondary(tag_sets=None)
- Parameters:
name – The name of the collection - a string.
codec_options – An instance of
CodecOptions. IfNone(the default) thecodec_optionsof thisDatabaseis used.read_preference – The read preference to use. If
None(the default) theread_preferenceof thisDatabaseis used. Seeread_preferencesfor options.write_concern – An instance of
WriteConcern. IfNone(the default) thewrite_concernof thisDatabaseis used.read_concern – An instance of
ReadConcern. IfNone(the default) theread_concernof thisDatabaseis used.
- coroutine list_collection_names(session: ClientSession | None = None, filter: Mapping[str, Any] | None = None, comment: Any | None = None, **kwargs: Any) list[str]¶
Get a list of all the collection names in this database.
For example, to list all non-system collections:
filter = {"name": {"$regex": r"^(?!system\.)"}} names = await db.list_collection_names(filter=filter)
- Parameters:
session (optional): a
ClientSession, created withstart_session().filter (optional): A query document to filter the list of collections returned from the listCollections command.
comment (optional): A user-provided comment to attach to this command.
**kwargs (optional): Optional parameters of the listCollections command. can be passed as keyword arguments to this method. The supported options differ by server version.
Changed in version 3.0: Added the
commentparameter.Changed in version 2.1: Added the
filterand**kwargsparameters.Added in version 1.2.
- coroutine async list_collections(session: ClientSession | None = None, filter: Mapping[str, Any] | None = None, comment: Any | None = None, **kwargs: Any) CommandCursor[MutableMapping[str, Any]]¶
Get a cursor over the collections of this database.
- Parameters:
session – a
ClientSession.filter – A query document to filter the list of collections returned from the listCollections command.
comment – A user-provided comment to attach to this command.
kwargs – Optional parameters of the listCollections command can be passed as keyword arguments to this method. The supported options differ by server version.
- Returns:
An instance of
CommandCursor.
- coroutine validate_collection(name_or_collection: str | Collection[_DocumentTypeArg], scandata: bool = False, full: bool = False, session: ClientSession | None = None, background: bool | None = None, comment: Any | None = None) dict[str, Any]¶
Validate a collection.
Returns a dict of validation info. Raises CollectionInvalid if validation fails.
See also the MongoDB documentation on the validate command.
- Parameters:
name_or_collection – A Collection object or the name of a collection to validate.
scandata – Do extra checks beyond checking the overall structure of the collection.
full – Have the server do a more thorough scan of the collection. Use with scandata for a thorough scan of the structure of the collection and the individual documents.
session – a
ClientSession.background – A boolean flag that determines whether the command runs in the background. Requires MongoDB 4.4+.
comment – A user-provided comment to attach to this command.
- 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 database.
Returns a
MotorChangeStreamcursor which iterates over changes on this database. 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
$changeStreamstage. Not all pipeline stages are valid after a$changeStreamstage, see the MongoDB documentation on change streams for the supported stages.full_document (optional): The fullDocument option to pass to the
$changeStreamstage. 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
Collationto 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:
Changed in version 3.2: Added
show_expanded_eventsparameter.Changed in version 3.1: Added
full_document_before_changeparameter.Changed in version 3.0: Added
commentparameter.Changed in version 2.1: Added the
start_afterparameter.Added in version 2.0.
- with_options(codec_options: CodecOptions[_DocumentTypeArg] | None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) Database[_DocumentType] | Database[_DocumentTypeArg]¶
Get a clone of this database changing the specified settings.
>>> db1.read_preference Primary() >>> from pymongo.read_preferences import Secondary >>> db2 = db1.with_options(read_preference=Secondary([{'node': 'analytics'}])) >>> db1.read_preference Primary() >>> db2.read_preference Secondary(tag_sets=[{'node': 'analytics'}], max_staleness=-1, hedge=None)
- Parameters:
codec_options – An instance of
CodecOptions. IfNone(the default) thecodec_optionsof thisCollectionis used.read_preference – The read preference to use. If
None(the default) theread_preferenceof thisCollectionis used. Seeread_preferencesfor options.write_concern – An instance of
WriteConcern. IfNone(the default) thewrite_concernof thisCollectionis used.read_concern – An instance of
ReadConcern. IfNone(the default) theread_concernof thisCollectionis used.
Added in version 3.8.
- property client¶
This MotorDatabase’s
MotorClient.
- property codec_options¶
Read only access to the
CodecOptionsof this instance.
- property name¶
The name of this
Database.
- property read_concern¶
Read only access to the
ReadConcernof 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_preferenceattribute is now read only.
- property write_concern¶
Read only access to the
WriteConcernof this instance.Changed in version 3.0: The
write_concernattribute is now read only.