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.
- 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 of
CodecOptions
. IfNone
(thedefault) client.codec_options is used. - read_preference (optional): The read preference to use. If
None
(the default) client.read_preference is used. - write_concern (optional): An instance of
WriteConcern
. IfNone
(thedefault) client.write_concern is used. - read_concern (optional): An instance of
ReadConcern
. IfNone
(thedefault) client.read_concern is used.
See also
The MongoDB documentation on
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
db[collection_name] || db.collection_name
- Get the collection_name
Collection
ofDatabase
db.
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
CodecOptions
of this instance.- 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
WriteConcern
of this instance.
Changed in version 3.0: The write_concern
attribute is now read only.
read_concern
- Read only access to the
ReadConcern
of this instance.
New in version 3.2.
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:
- db.command("createUser", "admin", pwd="password", roles=["root"])
To create a read-only user:
- db.command("createUser", "user", pwd="password", roles=["read"])
To change a password:
- db.command("updateUser", "user", pwd="newpassword")
Or change roles:
- 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:
- _name_: the name of the user to create
- _password_ (optional): the password of the user to create. Can notbe used with the <code>userSource</code> argument.
- _read_only_ (optional): if <code>True</code> the user will be read only
- _**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.
- _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
See the aggregation pipeline documentation for a list of stagesthat are supported.
Introduced in MongoDB 3.6.
- # Lists all operations currently running on the server.
- with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
- for operation in cursor:
- 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 of
Collation
.
The aggregate()
method obeys the read_preference
of thisDatabase
, except when $out
or $merge
are used, inwhich case PRIMARY
is 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:
- _pipeline_: a list of aggregation pipeline stages
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
- _**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
- This method authenticates the current connection, andwill also cause all new <code>socket</code> connectionsin the underlying client instance to be authenticated automatically.
- 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.
- 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:
- _name_: the name of the user to authenticate. Optional when_mechanism_ is MONGODB-X509 and the MongoDB server version is>= 3.4.
- _password_ (optional): the password of the user to authenticate.Not used with GSSAPI or MONGODB-X509 authentication.
- _source_ (optional): the database to authenticate on. If notspecified the current database is used.
- _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+.
- _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
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:
- _include_system_collections_ (optional): if <code>False</code> listwill not include system collections (e.g <code>system.indexes</code>)
- _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:
- >>> db.command("buildinfo")
For a command where the value matters, like {collstats:collection_name}
we can do:
- >>> db.command("collstats", collection_name)
For commands that take additional arguments we can usekwargs. So {filemd5: object_id, root: file_root}
becomes:
- >>> 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).
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.
-
value (optional): value to use for the command verb whencommand is passed as a string
-
check (optional): check the response for errors, raisingOperationFailure
if there are any
-
allowable_errors: if check is True
, error messagesin this list will be ignored by error-checking
-
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
.
-
codec_options: A CodecOptions
instance.
-
session (optional): AClientSession
.
-
**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
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:
- _name_: the name of the collection to create
- _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.
- _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.
- _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.
- _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.
- _collation_ (optional): An instance of[<code>Collation</code>]($f10fec00031f6158.md#pymongo.collation.Collation).
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
- _**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:
- # MongoDB 3.2 and 3.4
- client.admin.command("currentOp")
Or query the “inprog” virtual collection:
- # MongoDB 2.6 and 3.0
- client.admin["$cmd.sys.inprog"].find_one()
Parameters:
- _include_all_ (optional): if <code>True</code> also list currentlyidle operations in the result
- _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:
- _dbref_: the reference
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
- _**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.
Parameters:
- _name_or_collection_: the name of a collection to drop or thecollection object itself
- _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.
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.
Parameters:
- _code_: string representation of JavaScript code to beevaluated
- _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
.
- >>> 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[<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.
- _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.
- _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.
- _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.
Changed in version 3.5: Deprecated.
New in version 2.0.
Changed in version 3.5: Deprecated.
New in version 2.0.
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:
- filter = {"name": {"$regex": r"^(?!system\.)"}}
- db.list_collection_names(filter=filter)
Parameters:
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
- _filter_ (optional): A query document to filter the list ofcollections returned from the listCollections command.
- _**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:
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
- _filter_ (optional): A query document to filter the list ofcollections returned from the listCollections command.
- _**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.
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
.- DEPRECATED: All outgoing SON copying manipulators.
Changed in version 3.5: Deprecated.
New in version 2.0.
Changed in version 3.5: Deprecated.
New in version 2.0.
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.
Parameters:
- _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
Returns one of (OFF
,SLOW_ONLY
, ALL
).
Parameters:
- _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
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:
- db.command("dropUser", "user")
Parameters:
- _name_: the name of the user to remove
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
Changed in version 3.6: Added session
parameter. Deprecated remove_user.
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.
Parameters:
- _level_: Specifies a profiling level, see list of possible valuesbelow.
- _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.
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
Possible level values:
LevelSettingOFF
Off. No profiling.SLOW_ONLY
On. Only includes slow operations.ALL
On. 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
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:
- _name_or_collection_: A Collection object or the name of acollection to validate.
- _scandata_: Do extra checks beyond checking the overallstructure of the collection.
- _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.
- _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 $changeStream
stage and returns aDatabaseChangeStream
cursor whichiterates over changes on all collections in this database.
Introduced in MongoDB 4.0.
- with db.watch() as stream:
- for change in stream:
- 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.
- try:
- with db.watch(
- [{'$match': {'operationType': 'insert'}}]) as stream:
- for insert_change in stream:
- print(insert_change)
- except pymongo.errors.PyMongoError:
- # The ChangeStream 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:
- _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.
- _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.
- _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.
- _max_await_time_ms_ (optional): The maximum time in millisecondsfor the server to wait for changes before responding to a getMoreoperation.
- _batch_size_ (optional): The maximum number of documents to returnper batch.
- _collation_ (optional): The [<code>Collation</code>]($f10fec00031f6158.md#pymongo.collation.Collation)to use for the aggregation.
- _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 >= 4.0.
- _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.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:
A DatabaseChangeStream
cursor.
Changed in version 3.9: Added the start_after
parameter.
New in version 3.7.
See also
The MongoDB documentation on
withoptions
(_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[<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.
- _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.
- _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.
- _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.