MotorDatabase
¶
- class motor.motor_tornado.MotorDatabase(client, name, **kwargs)¶
- db[collection_name] || db.collection_name
Get the collection_name
MotorCollection
ofMotorDatabase
db.Raises
InvalidName
if an invalid collection name is used.
- aggregate(pipeline, **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_preference
is notPRIMARY
. Theaggregate()
method obeys theread_preference
of thisMotorDatabase
, except when$out
or$merge
are used, in which casePRIMARY
is 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
MotorCommandCursor
that 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_concern
of this database is automatically applied to this operation.New in version 2.1.
- coroutine command(command, value=1, check=True, allowable_errors=None, read_preference=None, codec_options=CodecOptions(document_class=dict, tz_aware=False, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler='strict', tzinfo=None, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None)), session=None, **kwargs)¶
Issue a MongoDB command.
Send command
command
to the database and return the response. Ifcommand
is a string then the command{command: value}
will be sent. Otherwise,command
must be adict
and 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
{collstats: collection_name}
we can do:result = await db.command("collstats", collection_name)
For commands that take additional arguments we can use kwargs. So
{filemd5: object_id, root: file_root}
becomes:result = await db.command("filemd5", object_id, root=file_root)
- 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
OperationFailure
if 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_preferences
for options.session (optional): a
ClientSession
, created withstart_session()
.**kwargs (optional): additional keyword arguments will be added to the command document before it is sent
Changed in version 1.2: Added session parameter.
- coroutine async create_collection(name, codec_options=None, read_preference=None, write_concern=None, read_concern=None, session=None, **kwargs)¶
Create a new
Collection
in this database.Normally collection creation is automatic. This method should only be used to specify options on creation.
CollectionInvalid
will be raised if the collection already exists.Options should be passed as keyword arguments to this method. Supported options vary with MongoDB release. Some examples include:
size
: desired initial size for the collection (in bytes). For capped collections this size is the max size of the collection.capped
: if True, this is a capped collectionmax
: maximum number of objects if capped (optional)timeseries
: a document specifying configuration options for timeseries collectionsexpireAfterSeconds
: the number of seconds after which a document in a timeseries collection expires
See the MongoDB documentation for a full list of supported options by server version.
- Parameters
name: the name of the collection to create
codec_options (optional): An instance of
CodecOptions
. IfNone
(the default) thecodec_options
of thisDatabase
is used.read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisDatabase
is used.write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisDatabase
is used.read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisDatabase
is used.collation (optional): An instance of
Collation
.session (optional): a
ClientSession
.**kwargs (optional): additional keyword arguments will be passed as options for the create collection command
- coroutine current_op(include_all=False, session=None)¶
DEPRECATED: Get information on operations currently running.
Starting with MongoDB 3.6 this helper is obsolete. The functionality provided by this helper is available in MongoDB 3.6+ using the $currentOp aggregation pipeline stage, which can be used with
aggregate()
. Note that, while this helper can only return a single document limited to a 16MB result,aggregate()
returns a cursor avoiding that limitation.Users of MongoDB versions older than 3.6 can use the currentOp command directly:
# MongoDB 3.2 and 3.4 await client.admin.command("currentOp")
Or query the “inprog” virtual collection:
# MongoDB 2.6 and 3.0 await client.admin["$cmd.sys.inprog"].find_one()
- Parameters
include_all (optional): if
True
also list currently idle operations in the resultsession (optional): a
ClientSession
, created withstart_session()
.
Changed in version 2.1: Deprecated, use
aggregate()
instead.Changed in version 1.2: Added session parameter.
- coroutine dereference(dbref, session=None, **kwargs)¶
Dereference a
DBRef
, getting the document it points to.Raises
TypeError
if dbref is not an instance ofDBRef
. Returns a document, orNone
if the reference does not point to a valid document. RaisesValueError
if dbref has a database specified that is different from the current database.- Parameters
dbref: the reference
session (optional): a
ClientSession
.**kwargs (optional): any additional keyword arguments are the same as the arguments to
find()
.
- coroutine drop_collection(name_or_collection, session=None)¶
Drop a collection.
- Parameters
name_or_collection: the name of a collection to drop or the collection object itself
session (optional): a
ClientSession
.
Note
The
write_concern
of this database is automatically applied to this operation when using MongoDB >= 3.4.
- get_collection(name, codec_options=None, read_preference=None, write_concern=None, read_concern=None)¶
Get a
Collection
with the given name and options.Useful for creating a
Collection
with 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 (optional): An instance of
CodecOptions
. IfNone
(the default) thecodec_options
of thisDatabase
is used.read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisDatabase
is used. Seeread_preferences
for options.write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisDatabase
is used.read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisDatabase
is used.
- coroutine list_collection_names(session=None, filter=None, **kwargs)¶
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.
**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 2.1: Added the
filter
and**kwargs
parameters.New in version 1.2.
- coroutine list_collections(session=None, filter=None, **kwargs)¶
Get a cursor over the collections of this database.
- Parameters
session (optional): a
ClientSession
.filter (optional): A query document to filter the list of collections returned from the listCollections 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.
- Returns
An instance of
CommandCursor
.
- coroutine profiling_info(session=None)¶
DEPRECATED: Returns a list containing current profiling information.
Starting with Motor 2.5, this helper is obsolete. Instead, users can view the database profiler output by running
find()
against thesystem.profile
collection as detailed in the profiler output documentation:profiling_info = await db["system.profile"].find().to_list()
- Parameters
session (optional): a
AsyncIOMotorClientSession
.
Changed in version 2.5: Deprecated.
- coroutine profiling_level(session=None)¶
DEPRECATED: Get the database’s current profiling level.
Starting with Motor 2.5, this helper is obsolete. Instead, users can run the profile command, using the
command()
helper to get the current profiler level. Running the profile command with the level set to-1
returns the current profiler information without changing it:res = await db.command("profile", -1) profiling_level = res["was"]
The format of
res
depends on the version of MongoDB in use.Returns one of (
OFF
,SLOW_ONLY
,ALL
).- Parameters
session (optional): a
AsyncIOMotorClientSession
.
Changed in version 2.5: Deprecated.
- coroutine set_profiling_level(level, slow_ms=None, session=None, sample_rate=None, filter=None)¶
DEPRECATED: Set the database’s profiling level.
Starting with Motor 2.5, this helper is obsolete. Instead, users can directly run the profile command, using the
command()
helper, e.g.:res = await db.command("profile", 2, filter={"op": "query"})
- Parameters
level: Specifies a profiling level, see list of possible values below.
slow_ms: Optionally modify the threshold for the profile to consider a query or operation. Even if the profiler is off queries slower than the slow_ms level will get written to the logs.
session (optional): a
AsyncIOMotorClientSession
.sample_rate (optional): The fraction of slow operations that should be profiled or logged expressed as a float between 0 and 1.
filter (optional): A filter expression that controls which operations are profiled and logged.
Possible level values:
Level
Setting
Off. No profiling.
On. Only includes slow operations.
On. Includes all operations.
Raises
ValueError
if level is not one of (OFF
,SLOW_ONLY
,ALL
).Changed in version 2.5: Added the
sample_rate
andfilter
parameters. Deprecated.
- coroutine validate_collection(name_or_collection, scandata=False, full=False, session=None, background=None)¶
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 (optional): a
ClientSession
.background (optional): A boolean flag that determines whether the command runs in the background. Requires MongoDB 4.4+.
- 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)¶
Watch changes on this database.
Returns a
MotorChangeStream
cursor 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
$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.
- Returns
Changed in version 2.1: Added the
start_after
parameter.New in version 2.0.
- with_options(codec_options=None, read_preference=None, write_concern=None, read_concern=None)¶
Get a clone of this database changing the specified settings.
>>> db1.read_preference Primary() >>> from pymongo import ReadPreference >>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY) >>> db1.read_preference Primary() >>> db2.read_preference Secondary(tag_sets=None)
- Parameters
codec_options (optional): An instance of
CodecOptions
. IfNone
(the default) thecodec_options
of thisCollection
is used.read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisCollection
is used. Seeread_preferences
for options.write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisCollection
is used.read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisCollection
is used.
New in version 3.8.
- property client¶
This MotorDatabase’s
MotorClient
.
- property codec_options¶
Read only access to the
CodecOptions
of this instance.
- property incoming_copying_manipulators¶
DEPRECATED: All incoming SON copying manipulators.
Changed in version 3.5: Deprecated.
New in version 2.0.
- property incoming_manipulators¶
DEPRECATED: All incoming SON manipulators.
Changed in version 3.5: Deprecated.
New in version 2.0.
- property name¶
The name of this
Database
.
- property outgoing_copying_manipulators¶
DEPRECATED: All outgoing SON copying manipulators.
Changed in version 3.5: Deprecated.
New in version 2.0.
- property outgoing_manipulators¶
DEPRECATED: All outgoing SON manipulators.
Changed in version 3.5: Deprecated.
New in version 2.0.
- property read_concern¶
Read only access to the
ReadConcern
of this instance.New 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 write_concern¶
Read only access to the
WriteConcern
of this instance.Changed in version 3.0: The
write_concern
attribute is now read only.