database – Database level operations (original) (raw)

Database level operations.

class pymongo.asynchronous.database.AsyncDatabase(client, name, codec_options=None, read_preference=None, write_concern=None, read_concern=None)

Get a database by client and name.

Raises TypeError if name is not an instance ofstr. Raises InvalidName ifname is not a valid database name.

Parameters:

See also

The MongoDB documentation on databases.

Changed in version 4.0: Removed the eval, system_js, error, last_status, previous_error, reset_error_history, authenticate, logout, collection_names, current_op, add_user, remove_user, profiling_level, set_profiling_level, and profiling_info methods. See the PyMongo 4 Migration Guide.

Changed in version 3.2: Added the read_concern option.

Changed in version 3.0: Added the codec_options, read_preference, and write_concern options.AsyncDatabase no longer returns an instance of AsyncCollection for attribute names with leading underscores. You must use dict-style lookups instead::

db[‘__my_collection__’]

Not:

db.__my_collection__

db[collection_name] || db.collection_name

Get the collection_name AsyncCollection ofAsyncDatabase db.

Raises InvalidName if an invalid collection name is used.

Note

Use dictionary style access if collection_name is an attribute of the AsyncDatabase class eg: db[collection_name].

__getitem__(name)

Get a collection of this database by name.

Raises InvalidName if an invalid collection name is used.

Parameters:

name (str) – the name of the collection to get

Return type:

AsyncCollection[__DocumentType_]

__getattr__(name)

Get a collection of this database by name.

Raises InvalidName if an invalid collection name is used.

Parameters:

name (str) – the name of the collection to get

Return type:

AsyncCollection[__DocumentType_]

codec_options

Read only access to the CodecOptionsof this instance.

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.

write_concern

Read only access to the WriteConcernof this instance.

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

read_concern

Read only access to the ReadConcernof this instance.

Added in version 3.2.

async aggregate(pipeline, session=None, **kwargs)

Perform a database-level aggregation.

See the aggregation pipeline documentation for a list of stages that are supported.

Lists all operations currently running on the server.

with client.admin.aggregate([{"$currentOp": {}}]) as cursor: for operation in cursor: print(operation)

The aggregate() method obeys the read_preference of thisAsyncDatabase, except when $out or $merge are used, in which case PRIMARYis used.

Note

This method does not support the ‘explain’ option. Please use command() instead.

Note

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

Parameters:

Return type:

AsyncCommandCursor[_DocumentType]

All optional aggregate command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:

Returns:

A AsyncCommandCursor over the result set.

Parameters:

Return type:

AsyncCommandCursor[_DocumentType]

Added in version 3.9.

property client_: AsyncMongoClient[_DocumentType]_

The client instance for this AsyncDatabase.

async 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: None = None, session: AsyncClientSession | None = None, comment: Any | None = None, **kwargs: Any) → dict[str, Any]

async 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: CodecOptions[_CodecDocumentType] = None, session: AsyncClientSession | None = None, comment: Any | None = None, **kwargs: Any) → _CodecDocumentType

Issue a MongoDB command.

Send command command to the database and return the response. If command is an instance of strthen the command {command: value} will be sent. Otherwise, command must be an instance ofdict and will be sent as is.

Any additional keyword arguments will be added to the final command document before it is sent.

For example, a command like {buildinfo: 1} can be sent using:

await db.command("buildinfo") OR await db.command({"buildinfo": 1})

For a command where the value matters, like {count: collection_name} we can do:

await db.command("count", collection_name) OR await db.command({"count": collection_name})

For commands that take additional arguments we can use kwargs. So {count: collection_name, query: query} becomes:

await db.command("count", collection_name, query=query) OR await db.command({"count": collection_name, "query": query})

Parameters:

Note

command() does not obey this AsyncDatabase’sread_preference or codec_options. You must use theread_preference and codec_options parameters 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.

Changed in version 3.6: Added session parameter.

Changed in version 3.0: Removed the as_class, fields, uuid_subtype, tag_sets, and secondary_acceptable_latency_ms option. Removed compile_re option: PyMongo now always represents BSON regular expressions as Regex objects. Usetry_compile() to attempt to convert from a BSON regular expression to a Python regular expression object. Added the codec_options parameter.

See also

The MongoDB documentation on commands.

async create_collection(name, codec_options=None, read_preference=None, write_concern=None, read_concern=None, session=None, check_exists=True, **kwargs)

Create a new AsyncCollection 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.

Parameters:

Return type:

AsyncCollection[_DocumentType]

All optional create collection command parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to:

Changed in version 4.2: Added the check_exists, clusteredIndex, and encryptedFields parameters.

Changed in version 3.11: This method is now supported inside multi-document transactions with MongoDB 4.4+.

Changed in version 3.6: Added session parameter.

Changed in version 3.4: Added the collation option.

Changed in version 3.0: Added the codec_options, read_preference, and write_concern options.

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:

Return type:

AsyncCommandCursor[_DocumentType]

Note

command() does not obey this AsyncDatabase’sread_preference or codec_options. You must use theread_preference and codec_options parameters 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.

async dereference(dbref, session=None, comment=None, **kwargs)

Dereference a DBRef, getting the document it points to.

Raises TypeError if dbref is not an instance ofDBRef. Returns a document, or None 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:

Return type:

Optional[_DocumentType]

Changed in version 4.1: Added comment parameter.

Changed in version 3.6: Added session parameter.

async drop_collection(name_or_collection, session=None, comment=None, encrypted_fields=None)

Drop a collection.

Parameters:

Return type:

dict[str, Any]

Note

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

Changed in version 4.2: Added encrypted_fields parameter.

Changed in version 4.1: Added comment parameter.

Changed in version 3.6: Added session parameter.

Changed in version 3.4: Apply this database’s write concern automatically to this operation when connected to MongoDB >= 3.4.

get_collection(name, codec_options=None, read_preference=None, write_concern=None, read_concern=None)

Get a AsyncCollection with the given name and options.

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

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:

Return type:

AsyncCollection[_DocumentType]

async list_collection_names(session=None, filter=None, comment=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.)"}} db.list_collection_names(filter=filter)

Parameters:

Return type:

list[str]

Changed in version 3.8: Added the filter and **kwargs parameters.

Added in version 3.6.

async list_collections(session=None, filter=None, comment=None, **kwargs)

Get a cursor over the collections of this database.

Parameters:

Returns:

An instance of AsyncCommandCursor.

Return type:

AsyncCommandCursor[MutableMapping[str, Any]]

Added in version 3.6.

property name_: str_

The name of this AsyncDatabase.

async validate_collection(name_or_collection, scandata=False, full=False, session=None, background=None, comment=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:

Return type:

dict[str, Any]

Changed in version 4.1: Added comment parameter.

Changed in version 3.11: Added background parameter.

Changed in version 3.6: Added session parameter.

async 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.

Performs an aggregation with an implicit initial $changeStreamstage and returns aAsyncDatabaseChangeStream cursor which iterates over changes on all collections in this database.

Introduced in MongoDB 4.0.

async with db.watch() as stream: async for change in stream: print(change)

The AsyncDatabaseChangeStream iterable blocks until the next change document is returned or an error is raised. If thenext() method encounters a network error when retrieving a batch from the server, it will automatically attempt to recreate the cursor such that no change events are missed. Any error encountered during the resume attempt indicates there may be an outage and will be raised.

try: async with db.watch([{"$match": {"operationType": "insert"}}]) as stream: async for insert_change in stream: print(insert_change) except pymongo.errors.PyMongoError: # The AsyncChangeStream encountered an unrecoverable error or the # resume attempt failed to recreate the cursor. logging.error("...")

For a precise description of the resume process see thechange streams specification.

Parameters:

Returns:

A AsyncDatabaseChangeStream cursor.

Return type:

AsyncDatabaseChangeStream[_DocumentType]

Changed in version 4.3: Added show_expanded_events parameter.

Changed in version 4.2: Added full_document_before_change parameter.

Changed in version 4.1: Added comment parameter.

Changed in version 3.9: Added the start_after parameter.

Added in version 3.7.

with_options(codec_options: None = None, read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) → AsyncDatabase[_DocumentType]

with_options(codec_options: bson.CodecOptions[_DocumentTypeArg], read_preference: _ServerMode | None = None, write_concern: WriteConcern | None = None, read_concern: ReadConcern | None = None) → AsyncDatabase[_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:

Added in version 3.8.