database – Database level operations

Database level operations.

  • pymongo.auth.MECHANISMS = frozenset(['MONGODB-X509', 'DEFAULT', 'PLAIN', 'GSSAPI', 'SCRAM-SHA-1', 'MONGODB-CR', 'SCRAM-SHA-256'])
  • The authentication mechanisms supported by PyMongo.
  • pymongo.OFF = 0
  • No database profiling.
  • pymongo.SLOWONLY = 1_
  • Only profile slow operations.
  • pymongo.ALL = 2
  • Profile all operations.
  • class pymongo.database.Database(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 ofbasestring (str in python 3). RaisesInvalidName if name is not a validdatabase name.

Parameters:

  • client: A MongoClient instance.
  • name: The database name.
  • codec_options (optional): An instance ofCodecOptions. If None (thedefault) client.codec_options is used.
  • read_preference (optional): The read preference to use. IfNone (the default) client.read_preference is used.
  • write_concern (optional): An instance ofWriteConcern. If None (thedefault) client.write_concern is used.
  • read_concern (optional): An instance ofReadConcern. If None (thedefault) client.read_concern is used.

See also

The MongoDB documentation on

databases

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.Database no longer returns an instanceof Collection for attribute nameswith leading underscores. You must use dict-style lookups instead::

db[‘my_collection’]

Not:

db.my_collection

Raises InvalidName if an invalid collectionname is used.

Note

Use dictionary style access if collection_name is anattribute of the Database class eg: db[collection_name].

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

New in version 3.2.

  • addson_manipulator(_manipulator)
  • Add a new son manipulator to this database.

DEPRECATED - add_son_manipulator is deprecated.

Changed in version 3.0: Deprecated add_son_manipulator.

  • adduser(_name, password=None, read_only=None, session=None, **kwargs)
  • DEPRECATED: Create user name with password password.

Add a new user with permissions for this Database.

Note

Will change the password if user name already exists.

Note

add_user is deprecated and will be removed in PyMongo4.0. Starting with MongoDB 2.6 user management is handled with fourdatabase commands, createUser, usersInfo, updateUser, anddropUser.

To create a user:

  1. db.command("createUser", "admin", pwd="password", roles=["root"])

To create a read-only user:

  1. db.command("createUser", "user", pwd="password", roles=["read"])

To change a password:

  1. db.command("updateUser", "user", pwd="newpassword")

Or change roles:

  1. db.command("updateUser", "user", roles=["readWrite"])

Warning

Never create or modify users over an insecure network withoutthe use of TLS. See TLS/SSL and PyMongo for more information.

Parameters:

  1. - _name_: the name of the user to create
  2. - _password_ (optional): the password of the user to create. Can notbe used with the <code>userSource</code> argument.
  3. - _read_only_ (optional): if <code>True</code> the user will be read only
  4. - _**kwargs_ (optional): optional fields for the user document(e.g. <code>userSource</code>, <code>otherDBRoles</code>, or <code>roles</code>). See[http://docs.mongodb.org/manual/reference/privilege-documents](http://docs.mongodb.org/manual/reference/privilege-documents)for more information.
  5. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.7: Added support for SCRAM-SHA-256 users with MongoDB 4.0 and later.

Changed in version 3.6: Added session parameter. Deprecated add_user.

Changed in version 2.5: Added kwargs support for optional fields introduced in MongoDB 2.4

Changed in version 2.2: Added support for read only users

  • aggregate(pipeline, session=None, **kwargs)
  • Perform a database-level aggregation.

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

Introduced in MongoDB 3.6.

  1. # Lists all operations currently running on the server.
  2. with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
  3. for operation in cursor:
  4. print(operation)

All optional aggregate command parameters should be passed askeyword arguments to this method. Valid options include, but are notlimited to:

  • allowDiskUse (bool): Enables writing to temporary files. When setto True, aggregation stages can write data to the _tmp subdirectoryof the –dbpath directory. The default is False.
  • maxTimeMS (int): The maximum amount of time to allow the operationto run in milliseconds.
  • batchSize (int): The maximum number of documents to return perbatch. Ignored if the connected mongod or mongos does not supportreturning aggregate results using a cursor.
  • collation (optional): An instance ofCollation.

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

Note

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

Note

The write_concern ofthis collection is automatically applied to this operation.

Parameters:

  1. - _pipeline_: a list of aggregation pipeline stages
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  3. - _**kwargs_ (optional): See list of options above.Returns:

A CommandCursor over the resultset.

New in version 3.9.

  • authenticate(name=None, password=None, source=None, mechanism='DEFAULT', **kwargs)
  • DEPRECATED: Authenticate to use this database.

Warning

Starting in MongoDB 3.6, calling authenticate()invalidates all existing cursors. It may also leave logical sessionsopen on the server for up to 30 minutes until they time out.

Authentication lasts for the life of the underlying clientinstance, or until logout() is called.

Raises TypeError if (required) name, (optional) password,or (optional) source is not an instance of basestring(str in python 3).

Note

  1. - This method authenticates the current connection, andwill also cause all new <code>socket</code> connectionsin the underlying client instance to be authenticated automatically.
  2. - Authenticating more than once on the same database with differentcredentials is not supported. You must call [<code>logout()</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.logout) beforeauthenticating with new credentials.
  3. - When sharing a client instance between multiple threads, allthreads will share the authentication. If you need differentauthentication profiles for different purposes you must usedistinct client instances.

Parameters:

  1. - _name_: the name of the user to authenticate. Optional when_mechanism_ is MONGODB-X509 and the MongoDB server version is&gt;= 3.4.
  2. - _password_ (optional): the password of the user to authenticate.Not used with GSSAPI or MONGODB-X509 authentication.
  3. - _source_ (optional): the database to authenticate on. If notspecified the current database is used.
  4. - _mechanism_ (optional): See [<code>MECHANISMS</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.auth.MECHANISMS) foroptions. If no mechanism is specified, PyMongo automatically usesMONGODB-CR when connected to a pre-3.0 version of MongoDB,SCRAM-SHA-1 when connected to MongoDB 3.0 through 3.6, andnegotiates the mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) whenconnected to MongoDB 4.0+.
  5. - _authMechanismProperties_ (optional): Used to specifyauthentication mechanism specific options. To specify the servicename for GSSAPI authentication passauthMechanismProperties=’SERVICE_NAME:<service name="">’

Changed in version 3.7: Added support for SCRAM-SHA-256 with MongoDB 4.0 and later.

Changed in version 3.5: Deprecated. Authenticating multiple users conflicts with support forlogical sessions in MongoDB 3.6. To authenticate as multiple users,create multiple instances of MongoClient.

New in version 2.8: Use SCRAM-SHA-1 with MongoDB 3.0 and later.

Changed in version 2.5: Added the source and mechanism parameters. authenticate()now raises a subclass of PyMongoError ifauthentication fails due to invalid credentials or configurationissues.

See also

The MongoDB documentation on

authenticate

  • client
  • The client instance for this Database.

  • collectionnames(_include_system_collections=True, session=None)

  • DEPRECATED: Get a list of all the collection names in thisdatabase.

Parameters:

  1. - _include_system_collections_ (optional): if <code>False</code> listwill not include system collections (e.g <code>system.indexes</code>)
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.7: Deprecated. Use list_collection_names() instead.

Changed in version 3.6: Added session parameter.

  • command(command, value=1, check=True, allowable_errors=None, read_preference=None, codec_options=CodecOptions(document_class=dict, tz_aware=False, uuid_representation=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 theresponse. If command is an instance of basestring(str in python 3) then 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 finalcommand document before it is sent.

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

  1. >>> db.command("buildinfo")

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

  1. >>> db.command("collstats", collection_name)

For commands that take additional arguments we can usekwargs. So {filemd5: object_id, root: file_root} becomes:

  1. >>> db.command("filemd5", object_id, root=file_root)

Parameters:

  1. -

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 issignificant (the “verb” must come first), so commandswhich require multiple keys (e.g. findandmodify)should use an instance of SON ora string and kwargs instead of a Python dict.

  1. -

value (optional): value to use for the command verb whencommand is passed as a string

  1. -

check (optional): check the response for errors, raisingOperationFailure if there are any

  1. -

allowable_errors: if check is True, error messagesin this list will be ignored by error-checking

  1. -

read_preference (optional): The read preference for thisoperation. See read_preferences for options.If the provided session is in a transaction, defaults to theread preference configured for the transaction.Otherwise, defaults toPRIMARY.

  1. -

codec_options: A CodecOptionsinstance.

  1. -

session (optional): AClientSession.

  1. -

**kwargs (optional): additional keyword arguments willbe added to the command document before it is sent

Note

command() does not obey this Database’sread_preference or codec_options. You must use theread_preference and codec_options parameters instead.

Note

command() does not apply any custom TypeDecoderswhen decoding the command response.

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 BSONregular expressions as Regex objects. Usetry_compile() to attempt to convert from aBSON regular expression to a Python regular expression object.Added the codec_options parameter.

Changed in version 2.7: Added compile_re option. If set to False, PyMongo represented BSONregular expressions as Regex objects instead ofattempting to compile BSON regular expressions as Python nativeregular expressions, thus preventing errors for some incompatiblepatterns, see PYTHON-500.

Changed in version 2.3: Added tag_sets and secondary_acceptable_latency_ms options.

Changed in version 2.2: Added support for as_class - the class you want to use forthe resulting documents

See also

The MongoDB documentation on

commands

  • createcollection(_name, codec_options=None, read_preference=None, write_concern=None, read_concern=None, session=None, **kwargs)
  • Create a new Collection in thisdatabase.

Normally collection creation is automatic. This method shouldonly be used to specify options oncreation. CollectionInvalid will beraised if the collection already exists.

Options should be passed as keyword arguments to this method. Supportedoptions vary with MongoDB release. Some examples include:

  • “size”: desired initial size for the collection (inbytes). For capped collections this size is the maxsize of the collection.
  • “capped”: if True, this is a capped collection
  • “max”: maximum number of objects if capped (optional)

See the MongoDB documentation for a full list of supported options byserver version.

Parameters:

  1. - _name_: the name of the collection to create
  2. - _codec_options_ (optional): An instance of[<code>CodecOptions</code>]($f5dfe349e82ce60f.md#bson.codec_options.CodecOptions). If <code>None</code> (thedefault) the [<code>codec_options</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.codec_options) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  3. - _read_preference_ (optional): The read preference to use. If<code>None</code> (the default) the [<code>read_preference</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_preference) of this[<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) is used.
  4. - _write_concern_ (optional): An instance of[<code>WriteConcern</code>]($1c33c29d27c9df5c.md#pymongo.write_concern.WriteConcern). If <code>None</code> (thedefault) the [<code>write_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.write_concern) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  5. - _read_concern_ (optional): An instance of[<code>ReadConcern</code>]($ba6aec8e2bd5e77f.md#pymongo.read_concern.ReadConcern). If <code>None</code> (thedefault) the [<code>read_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_concern) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  6. - _collation_ (optional): An instance of[<code>Collation</code>]($f10fec00031f6158.md#pymongo.collation.Collation).
  7. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  8. - _**kwargs_ (optional): additional keyword arguments willbe passed as options for the create collection command

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.

Changed in version 2.2: Removed deprecated argument: options

  • currentop(_include_all=False, session=None)
  • DEPRECATED: Get information on operations currently running.

Starting with MongoDB 3.6 this helper is obsolete. The functionalityprovided by this helper is available in MongoDB 3.6+ using the$currentOp aggregation pipeline stage, which can be used withaggregate(). Note that, while this helper can only returna 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 commanddirectly:

  1. # MongoDB 3.2 and 3.4
  2. client.admin.command("currentOp")

Or query the “inprog” virtual collection:

  1. # MongoDB 2.6 and 3.0
  2. client.admin["$cmd.sys.inprog"].find_one()

Parameters:

  1. - _include_all_ (optional): if <code>True</code> also list currentlyidle operations in the result
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.9: Deprecated.

Changed in version 3.6: Added session parameter.

  • dereference(dbref, session=None, **kwargs)
  • Dereference a DBRef, getting thedocument it points to.

Raises TypeError if dbref is not an instance ofDBRef. Returns a document, or None ifthe reference does not point to a valid document. RaisesValueError if dbref has a database specified thatis different from the current database.

Parameters:

  1. - _dbref_: the reference
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  3. - _**kwargs_ (optional): any additional keyword argumentsare the same as the arguments to[<code>find()</code>]($93912a58b0c5f9d1.md#pymongo.collection.Collection.find).

Changed in version 3.6: Added session parameter.

  • dropcollection(_name_or_collection, session=None)
  • Drop a collection.

Parameters:

  1. - _name_or_collection_: the name of a collection to drop or thecollection object itself
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Note

The write_concern ofthis database is automatically applied to this operation when usingMongoDB >= 3.4.

Changed in version 3.6: Added session parameter.

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

  • error()
  • DEPRECATED: Get the error if one occurred on the last operation.

This method is obsolete: all MongoDB write operations (insert, update,remove, and so on) use the write concern w=1 and report theirerrors by default.

Changed in version 2.8: Deprecated.

  • eval(code, *args)
  • DEPRECATED: Evaluate a JavaScript expression in MongoDB.

Parameters:

  1. - _code_: string representation of JavaScript code to beevaluated
  2. - _args_ (optional): additional positional arguments arepassed to the _code_ being evaluated

Warning

the eval command is deprecated in MongoDB 3.0 andwill be removed in a future server version.

  • getcollection(_name, codec_options=None, read_preference=None, write_concern=None, read_concern=None)
  • Get a Collection with the given nameand options.

Useful for creating a Collection withdifferent codec options, read preference, and/or write concern fromthis Database.

  1. >>> db.read_preference
  2. Primary()
  3. >>> coll1 = db.test
  4. >>> coll1.read_preference
  5. Primary()
  6. >>> from pymongo import ReadPreference
  7. >>> coll2 = db.get_collection(
  8. ... 'test', read_preference=ReadPreference.SECONDARY)
  9. >>> coll2.read_preference
  10. Secondary(tag_sets=None)

Parameters:

  1. - _name_: The name of the collection - a string.
  2. - _codec_options_ (optional): An instance of[<code>CodecOptions</code>]($f5dfe349e82ce60f.md#bson.codec_options.CodecOptions). If <code>None</code> (thedefault) the [<code>codec_options</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.codec_options) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  3. - _read_preference_ (optional): The read preference to use. If<code>None</code> (the default) the [<code>read_preference</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_preference) of this[<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) is used. See [<code>read_preferences</code>]($4f651614045067e6.md#module-pymongo.read_preferences)for options.
  4. - _write_concern_ (optional): An instance of[<code>WriteConcern</code>]($1c33c29d27c9df5c.md#pymongo.write_concern.WriteConcern). If <code>None</code> (thedefault) the [<code>write_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.write_concern) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  5. - _read_concern_ (optional): An instance of[<code>ReadConcern</code>]($ba6aec8e2bd5e77f.md#pymongo.read_concern.ReadConcern). If <code>None</code> (thedefault) the [<code>read_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_concern) of this [<code>Database</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database) isused.
  • incoming_copying_manipulators
  • DEPRECATED: All incoming SON copying manipulators.

Changed in version 3.5: Deprecated.

New in version 2.0.

  • incoming_manipulators
  • DEPRECATED: All incoming SON manipulators.

Changed in version 3.5: Deprecated.

New in version 2.0.

  • last_status()
  • DEPRECATED: Get status information from the last operation.

This method is obsolete: all MongoDB write operations (insert, update,remove, and so on) use the write concern w=1 and report theirerrors by default.

Returns a SON object with status information.

Changed in version 2.8: Deprecated.

  • listcollection_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:

  1. filter = {"name": {"$regex": r"^(?!system\.)"}}
  2. db.list_collection_names(filter=filter)

Parameters:

  1. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  2. - _filter_ (optional): A query document to filter the list ofcollections returned from the listCollections command.
  3. - _**kwargs_ (optional): Optional parameters of the[listCollections command](https://docs.mongodb.com/manual/reference/command/listCollections/)can be passed as keyword arguments to this method. The supportedoptions differ by server version.

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

New in version 3.6.

  • listcollections(_session=None, filter=None, **kwargs)
  • Get a cursor over the collectons of this database.

Parameters:

  1. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  2. - _filter_ (optional): A query document to filter the list ofcollections returned from the listCollections command.
  3. - _**kwargs_ (optional): Optional parameters of the[listCollections command](https://docs.mongodb.com/manual/reference/command/listCollections/)can be passed as keyword arguments to this method. The supportedoptions differ by server version.Returns:

An instance of CommandCursor.

New in version 3.6.

  • logout()
  • DEPRECATED: Deauthorize use of this database.

Warning

Starting in MongoDB 3.6, calling logout()invalidates all existing cursors. It may also leave logical sessionsopen on the server for up to 30 minutes until they time out.

  • name
  • The name of this Database.

  • outgoing_copying_manipulators

  • DEPRECATED: All outgoing SON copying manipulators.

Changed in version 3.5: Deprecated.

New in version 2.0.

  • outgoing_manipulators
  • DEPRECATED: All outgoing SON manipulators.

Changed in version 3.5: Deprecated.

New in version 2.0.

  • previous_error()
  • DEPRECATED: Get the most recent error on this database.

This method is obsolete: all MongoDB write operations (insert, update,remove, and so on) use the write concern w=1 and report theirerrors by default.

Only returns errors that have occurred since the last call toreset_error_history(). Returns None if no such errors haveoccurred.

Changed in version 2.8: Deprecated.

  • profilinginfo(_session=None)
  • Returns a list containing current profiling information.

Parameters:

  1. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.6: Added session parameter.

See also

The MongoDB documentation on

profiling

  • profilinglevel(_session=None)
  • Get the database’s current profiling level.

Returns one of (OFF,SLOW_ONLY, ALL).

Parameters:

  1. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.6: Added session parameter.

See also

The MongoDB documentation on

profiling

  • removeuser(_name, session=None)
  • DEPRECATED: Remove user name from this Database.

User name will no longer have permissions to access thisDatabase.

Note

remove_user is deprecated and will be removed in PyMongo4.0. Use the dropUser command instead:

  1. db.command("dropUser", "user")

Parameters:

  1. - _name_: the name of the user to remove
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.6: Added session parameter. Deprecated remove_user.

  • reset_error_history()
  • DEPRECATED: Reset the error history of this database.

This method is obsolete: all MongoDB write operations (insert, update,remove, and so on) use the write concern w=1 and report theirerrors by default.

Calls to previous_error() will only return errors that haveoccurred since the most recent call to this method.

Changed in version 2.8: Deprecated.

  • setprofiling_level(_level, slow_ms=None, session=None)
  • Set the database’s profiling level.

Parameters:

  1. - _level_: Specifies a profiling level, see list of possible valuesbelow.
  2. - _slow_ms_: Optionally modify the threshold for the profile toconsider a query or operation. Even if the profiler is off queriesslower than the _slow_ms_ level will get written to the logs.
  3. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Possible level values:

LevelSettingOFFOff. No profiling.SLOW_ONLYOn. Only includes slow operations.ALLOn. Includes all operations.

Raises ValueError if level is not one of(OFF, SLOW_ONLY,ALL).

Changed in version 3.6: Added session parameter.

See also

The MongoDB documentation on

profiling

See the documentation for SystemJS for more details.

  • validatecollection(_name_or_collection, scandata=False, full=False, session=None)
  • Validate a collection.

Returns a dict of validation info. Raises CollectionInvalid ifvalidation fails.

Parameters:

  1. - _name_or_collection_: A Collection object or the name of acollection to validate.
  2. - _scandata_: Do extra checks beyond checking the overallstructure of the collection.
  3. - _full_: Have the server do a more thorough scan of thecollection. Use with _scandata_ for a thorough scanof the structure of the collection and the individualdocuments.
  4. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.6: Added session parameter.

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

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

Introduced in MongoDB 4.0.

  1. with db.watch() as stream:
  2. for change in stream:
  3. print(change)

The DatabaseChangeStream iterableblocks until the next change document is returned or an error israised. If thenext() methodencounters a network error when retrieving a batch from the server,it will automatically attempt to recreate the cursor such that nochange events are missed. Any error encountered during the resumeattempt indicates there may be an outage and will be raised.

  1. try:
  2. with db.watch(
  3. [{'$match': {'operationType': 'insert'}}]) as stream:
  4. for insert_change in stream:
  5. print(insert_change)
  6. except pymongo.errors.PyMongoError:
  7. # The ChangeStream encountered an unrecoverable error or the
  8. # resume attempt failed to recreate the cursor.
  9. logging.error('...')

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

Parameters:

  1. - _pipeline_ (optional): A list of aggregation pipeline stages toappend to an initial <code>$changeStream</code> stage. Not allpipeline stages are valid after a <code>$changeStream</code> stage, see theMongoDB documentation on change streams for the supported stages.
  2. - _full_document_ (optional): The fullDocument to pass as an optionto the <code>$changeStream</code> stage. Allowed values: updateLookup’.When set to updateLookup’, the change notification for partialupdates will include both a delta describing the changes to thedocument, as well as a copy of the entire document that waschanged from some time after the change occurred.
  3. - _resume_after_ (optional): A resume token. If provided, thechange stream will start returning changes that occur directlyafter the operation specified in the resume token. A resume tokenis the _id value of a change document.
  4. - _max_await_time_ms_ (optional): The maximum time in millisecondsfor the server to wait for changes before responding to a getMoreoperation.
  5. - _batch_size_ (optional): The maximum number of documents to returnper batch.
  6. - _collation_ (optional): The [<code>Collation</code>]($f10fec00031f6158.md#pymongo.collation.Collation)to use for the aggregation.
  7. - _start_at_operation_time_ (optional): If provided, the resultingchange stream will only return changes that occurred at or afterthe specified [<code>Timestamp</code>]($f7f66b49fcfee58c.md#bson.timestamp.Timestamp). RequiresMongoDB &gt;= 4.0.
  8. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  9. - _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:

A DatabaseChangeStream cursor.

Changed in version 3.9: Added the start_after parameter.

New in version 3.7.

See also

The MongoDB documentation on

changeStreams

  • withoptions(_codec_options=None, read_preference=None, write_concern=None, read_concern=None)
  • Get a clone of this database changing the specified settings.
  1. >>> db1.read_preference
  2. Primary()
  3. >>> from pymongo import ReadPreference
  4. >>> db2 = db1.with_options(read_preference=ReadPreference.SECONDARY)
  5. >>> db1.read_preference
  6. Primary()
  7. >>> db2.read_preference
  8. Secondary(tag_sets=None)

Parameters:

  1. - _codec_options_ (optional): An instance of[<code>CodecOptions</code>]($f5dfe349e82ce60f.md#bson.codec_options.CodecOptions). If <code>None</code> (thedefault) the [<code>codec_options</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.codec_options) of this <code>Collection</code>is used.
  2. - _read_preference_ (optional): The read preference to use. If<code>None</code> (the default) the [<code>read_preference</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_preference) of this<code>Collection</code> is used. See [<code>read_preferences</code>]($4f651614045067e6.md#module-pymongo.read_preferences)for options.
  3. - _write_concern_ (optional): An instance of[<code>WriteConcern</code>]($1c33c29d27c9df5c.md#pymongo.write_concern.WriteConcern). If <code>None</code> (thedefault) the [<code>write_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.write_concern) of this <code>Collection</code>is used.
  4. - _read_concern_ (optional): An instance of[<code>ReadConcern</code>]($ba6aec8e2bd5e77f.md#pymongo.read_concern.ReadConcern). If <code>None</code> (thedefault) the [<code>read_concern</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.database.Database.read_concern) of this <code>Collection</code>is used.

New in version 3.8.

  • class pymongo.database.SystemJS(database)
  • DEPRECATED: Get a system js helper for the database database.

SystemJS will be removed in PyMongo 4.0.

  • list()
  • Get a list of the names of the functions stored in this database.