mongo_client – Tools for connecting to MongoDB

Tools for connecting to MongoDB.

See also

High Availability and PyMongo for examples of connectingto replica sets or sets of mongos servers.

To get a Database instance from aMongoClient use either dictionary-style or attribute-styleaccess:

  1. >>> from pymongo import MongoClient
  2. >>> c = MongoClient()
  3. >>> c.test_database
  4. Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test_database')
  5. >>> c['test-database']
  6. Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test-database')
  • class pymongo.mongoclient.MongoClient(_host='localhost', port=27017, document_class=dict, tz_aware=False, connect=True, **kwargs)
  • Client for a MongoDB instance, a replica set, or a set of mongoses.

The client object is thread-safe and has connection-pooling built in.If an operation fails because of a network error,ConnectionFailure is raised and the clientreconnects in the background. Application code should handle thisexception (recognizing that the operation failed) and then continue toexecute.

The host parameter can be a full mongodb URI, in addition toa simple hostname. It can also be a list of hostnames orURIs. Any port specified in the host string(s) will overridethe port parameter. If multiple mongodb URIs containingdatabase or auth information are passed, the last database,username, and password present will be used. For username andpasswords reserved characters like ‘:’, ‘/’, ‘+’ and ‘@’ must bepercent encoded following RFC 2396:

  1. try:
  2. # Python 3.x
  3. from urllib.parse import quote_plus
  4. except ImportError:
  5. # Python 2.x
  6. from urllib import quote_plus
  7.  
  8. uri = "mongodb://%s:%s@%s" % (
  9. quote_plus(user), quote_plus(password), host)
  10. client = MongoClient(uri)

Unix domain sockets are also supported. The socket path must be percentencoded in the URI:

  1. uri = "mongodb://%s:%s@%s" % (
  2. quote_plus(user), quote_plus(password), quote_plus(socket_path))
  3. client = MongoClient(uri)

But not when passed as a simple hostname:

  1. client = MongoClient('/tmp/mongodb-27017.sock')

Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. TheURI must include one, and only one, hostname. The hostname will beresolved to one or more DNS SRV records which will be usedas the seed list for connecting to the MongoDB deployment. When usingSRV URIs, the authSource and replicaSet configuration options canbe specified using TXT records. See theInitial DNS Seedlist Discovery specfor more details. Note that the use of SRV URIs implicitly enablesTLS support. Pass tls=false in the URI to override.

Note

MongoClient creation will block waiting for answers fromDNS when mongodb+srv:// URIs are used.

Note

Starting with version 3.0 the MongoClientconstructor no longer blocks while connecting to the server orservers, and it no longer raisesConnectionFailure if they areunavailable, nor ConfigurationErrorif the user’s credentials are wrong. Instead, the constructorreturns immediately and launches the connection process onbackground threads. You can check if the server is availablelike this:

  1. from pymongo.errors import ConnectionFailure
  2. client = MongoClient()
  3. try:
  4. # The ismaster command is cheap and does not require auth.
  5. client.admin.command('ismaster')
  6. except ConnectionFailure:
  7. print("Server not available")

Warning

When using PyMongo in a multiprocessing context, pleaseread Using PyMongo with Multiprocessing first.

Note

Many of the following options can be passed using a MongoDBURI or keyword parameters. If the same option is passed in a URI andas a keyword parameter the keyword parameter takes precedence.

Parameters:

  • host (optional): hostname or IP address or Unix domain socketpath of a single mongod or mongos instance to connect to, or amongodb URI, or a list of hostnames / mongodb URIs. If host isan IPv6 literal it must be enclosed in ‘[‘ and ‘]’ charactersfollowing the RFC2732 URL syntax (e.g. ‘[::1]’ for localhost).Multihomed and round robin DNS addresses are not supported.
  • port (optional): port number on which to connect
  • document_class (optional): default class to use fordocuments returned from queries on this client
  • type_registry (optional): instance ofTypeRegistry to enable encodingand decoding of custom types.
  • tz_aware (optional): if True,datetime instances returned as valuesin a document by this MongoClient will be timezoneaware (otherwise they will be naive)
  • connect (optional): if True (the default), immediatelybegin connecting to MongoDB in the background. Otherwise connecton the first operation.

Other optional parameters can be passed as keyword arguments:

  • maxPoolSize (optional): The maximum allowable number ofconcurrent connections to each connected server. Requests to aserver will block if there are maxPoolSize outstandingconnections to the requested server. Defaults to 100. Cannot be 0.

  • minPoolSize (optional): The minimum required number of concurrentconnections that the pool will maintain to each connected server.Default is 0.

  • maxIdleTimeMS (optional): The maximum number of milliseconds thata connection can remain idle in the pool before being removed andreplaced. Defaults to None (no limit).

  • socketTimeoutMS: (integer or None) Controls how long (inmilliseconds) the driver will wait for a response after sending anordinary (non-monitoring) database operation before concluding thata network error has occurred. Defaults to None (no timeout).

  • connectTimeoutMS: (integer or None) Controls how long (inmilliseconds) the driver will wait during server monitoring whenconnecting a new socket to a server before concluding the serveris unavailable. Defaults to 20000 (20 seconds).

  • server_selector: (callable or None) Optional, user-providedfunction that augments server selection rules. The function shouldaccept as an argument a list ofServerDescription objects andreturn a list of server descriptions that should be consideredsuitable for the desired operation.

  • serverSelectionTimeoutMS: (integer) Controls how long (inmilliseconds) the driver will wait to find an available,appropriate server to carry out a database operation; while it iswaiting, multiple server monitoring operations may be carried out,each controlled by connectTimeoutMS. Defaults to 30000 (30seconds).

  • waitQueueTimeoutMS: (integer or None) How long (in milliseconds)a thread will wait for a socket from the pool if the pool has nofree sockets. Defaults to None (no timeout).

  • waitQueueMultiple: (integer or None) Multiplied by maxPoolSizeto give the number of threads allowed to wait for a socket at onetime. Defaults to None (no limit).

  • heartbeatFrequencyMS: (optional) The number of millisecondsbetween periodic server checks, or None to accept the defaultfrequency of 10 seconds.

  • appname: (string or None) The name of the application thatcreated this MongoClient instance. MongoDB 3.4 and newer willprint this value in the server log upon establishing eachconnection. It is also recorded in the slow query log andprofile collections.

  • driver: (pair or None) A driver implemented on top of PyMongo canpass a DriverInfo to add its name,version, and platform to the message printed in the server log whenestablishing a connection.

  • event_listeners: a list or tuple of event listeners. Seemonitoring for details.

  • retryWrites: (boolean) Whether supported write operationsexecuted within this MongoClient will be retried once after anetwork error on MongoDB 3.6+. Defaults to True.The supported write operations are:

Unsupported write operations include, but are not limited to,aggregate() using the $outpipeline operator and any operation with an unacknowledged writeconcern (e.g. {w: 0})). Seehttps://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst

Unsupported read operations include, but are not limited to:map_reduce(),inline_map_reduce(),command(),and any getMore operation on a cursor.

Enabling retryable reads makes applications more resilient totransient errors such as network failures, database upgrades, andreplica set failovers. For an exact definition of which errorstrigger a retry, see the retryable reads specification.

  • socketKeepAlive: (boolean) DEPRECATED Whether to sendperiodic keep-alive packets on connected sockets. Defaults toTrue. Disabling it is not recommended, seehttps://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments”,

  • compressors: Comma separated list of compressors for wireprotocol compression. The list is used to negotiate a compressorwith the server. Currently supported options are “snappy”, “zlib”and “zstd”. Support for snappy requires thepython-snappy package.zlib support requires the Python standard library zlib module. zstdrequires the zstandardpackage. By default no compression is used. Compression supportmust also be enabled on the server. MongoDB 3.4+ supports snappycompression. MongoDB 3.6 adds support for zlib. MongoDB 4.2 addssupport for zstd.

  • zlibCompressionLevel: (int) The zlib compression level to usewhen zlib is used as the wire protocol compressor. Supported valuesare -1 through 9. -1 tells the zlib library to use its defaultcompression level (usually 6). 0 means no compression. 1 is bestspeed. 9 is best compression. Defaults to -1.

  • uuidRepresentation: The BSON representation to use when encodingfrom and decoding to instances of UUID. Validvalues are pythonLegacy (the default), javaLegacy,csharpLegacy and standard. New applications should considersetting this to standard for cross language compatibility.

Write Concern options:

(Only set if passed. No default values.)

  • w: (integer or string) If this is a replica set, write operationswill block until they have been replicated to the specified numberor tagged set of servers. w= always includes the replica setprimary (e.g. w=3 means write to the primary and wait untilreplicated to two secondaries). Passing w=0 disables writeacknowledgement and all other write concern options.
  • wTimeoutMS: (integer) Used in conjunction with w. Specify a valuein milliseconds to control how long to wait for write propagationto complete. If replication does not complete in the giventimeframe, a timeout exception is raised. Passing wTimeoutMS=0will cause write operations to wait indefinitely.
  • journal: If True block until write operations have beencommitted to the journal. Cannot be used in combination withfsync. Prior to MongoDB 2.6 this option was ignored if the serverwas running without journaling. Starting with MongoDB 2.6 writeoperations will fail with an exception if this option is used whenthe server is running without journaling.
  • fsync: If True and the server is running without journaling,blocks until the server has synced all data files to disk. If theserver is running with journaling, this acts the same as the j_option, blocking until write operations have been committed to thejournal. Cannot be used in combination with _j.

Replica set keyword arguments for connecting with a replica set- either directly or via a mongos:

  • replicaSet: (string or None) The name of the replica set toconnect to. The driver will verify that all servers it connects tomatch this name. Implies that the hosts specified are a seed listand the driver should attempt to find all members of the set.Defaults to None.

Read Preference:

  • readPreference: The replica set read preference for this client.One of primary, primaryPreferred, secondary,secondaryPreferred, or nearest. Defaults to primary.
  • readPreferenceTags: Specifies a tag set as a comma-separated listof colon-separated key-value pairs. For example dc:ny,rack:1.Defaults to None.
  • maxStalenessSeconds: (integer) The maximum estimatedlength of time a replica set secondary can fall behind the primaryin replication before it will no longer be selected for operations.Defaults to -1, meaning no maximum. If maxStalenessSecondsis set, it must be a positive integer greater than or equal to90 seconds.

See also

Server Selector Example

Authentication:

  • username: A string.

  • password: A string.

Although username and password must be percent-escaped in a MongoDBURI, they must not be percent-escaped when passed as parameters. Inthis example, both the space and slash special characters are passedas-is:

  1. MongoClient(username="user name", password="pass/word")
  • authSource: The database to authenticate on. Defaults to thedatabase specified in the URI, if provided, or to “admin”.

  • authMechanism: See MECHANISMS for options.If no mechanism is specified, PyMongo automatically uses MONGODB-CRwhen connected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 whenconnected to MongoDB 3.0 through 3.6, and negotiates the mechanismto use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB4.0+.

  • authMechanismProperties: Used to specify authentication mechanismspecific options. To specify the service name for GSSAPIauthentication pass authMechanismProperties=’SERVICE_NAME:

See also

Authentication Examples

TLS/SSL configuration:

  • tls: (boolean) If True, create the connection to the serverusing transport layer security. Defaults to False.
  • tlsInsecure: (boolean) Specify whether TLS constraints should berelaxed as much as possible. Setting tlsInsecure=True impliestlsAllowInvalidCertificates=True andtlsAllowInvalidHostnames=True. Defaults to False. Thinkvery carefully before setting this to True as it dramaticallyreduces the security of TLS.
  • tlsAllowInvalidCertificates: (boolean) If True, continuesthe TLS handshake regardless of the outcome of the certificateverification process. If this is False, and a value is notprovided for tlsCAFile, PyMongo will attempt to load systemprovided CA certificates. If the python version in use does notsupport loading system CA certificates then the tlsCAFileparameter must point to a file of CA certificates.tlsAllowInvalidCertificates=False implies tls=True.Defaults to False. Think very carefully before setting thisto True as that could make your application vulnerable toman-in-the-middle attacks.
  • tlsAllowInvalidHostnames: (boolean) If True, disables TLShostname verification. tlsAllowInvalidHostnames=False impliestls=True. Defaults to False. Think very carefully beforesetting this to True as that could make your applicationvulnerable to man-in-the-middle attacks.
  • tlsCAFile: A file containing a single or a bundle of“certification authority” certificates, which are used to validatecertificates passed from the other end of the connection.Implies tls=True. Defaults to None.
  • tlsCertificateKeyFile: A file containing the client certificateand private key. If you want to pass the certificate and privatekey as separate files, use the ssl_certfile and ssl_keyfileoptions instead. Implies tls=True. Defaults to None.
  • tlsCRLFile: A file containing a PEM or DER formattedcertificate revocation list. Only supported by python 2.7.9+(pypy 2.5.1+). Implies tls=True. Defaults to None.
  • tlsCertificateKeyFilePassword: The password or passphrase fordecrypting the private key in tlsCertificateKeyFile orssl_keyfile. Only necessary if the private key is encrypted.Only supported by python 2.7.9+ (pypy 2.5.1+) and 3.3+. Defaultsto None.
  • ssl: (boolean) Alias for tls.
  • ssl_certfile: The certificate file used to identify the localconnection against mongod. Implies tls=True. Defaults toNone.
  • ssl_keyfile: The private keyfile used to identify the localconnection against mongod. Can be omitted if the keyfile isincluded with the tlsCertificateKeyFile. Implies tls=True.Defaults to None.

Read Concern options:

(If not set explicitly, this will use the server default)

  • readConcernLevel: (string) The read concern level specifies thelevel of isolation for read operations. For example, a readoperation using a read concern level of majority will onlyreturn data that has been written to a majority of nodes. If thelevel is left unspecified, the server default will be used.

Client side encryption options:

(If not set explicitly, client side encryption will not be enabled.)

  • auto_encryption_opts: AAutoEncryptionOpts whichconfigures this client to automatically encrypt collection commandsand automatically decrypt results. Support for client sideencryption is in beta. Backwards-breaking changes may be madebefore the final release.

See also

The MongoDB documentation on

connections

Changed in version 3.9: Added the retryReads keyword argument and URI option.Added the tlsInsecure keyword argument and URI option.The following keyword arguments and URI options were deprecated:

  • wTimeout was deprecated in favor of wTimeoutMS.
  • j was deprecated in favor of journal.
  • ssl_cert_reqs was deprecated in favor oftlsAllowInvalidCertificates.
  • ssl_match_hostname was deprecated in favor oftlsAllowInvalidHostnames.
  • ssl_ca_certs was deprecated in favor of tlsCAFile.
  • ssl_certfile was deprecated in favor oftlsCertificateKeyFile.
  • ssl_crlfile was deprecated in favor of tlsCRLFile.
  • ssl_pem_passphrase was deprecated in favor oftlsCertificateKeyFilePassword.

Changed in version 3.9: retryWrites now defaults to True.

Changed in version 3.8: Added the server_selector keyword argument.Added the type_registry keyword argument.

Changed in version 3.7: Added the driver keyword argument.

Changed in version 3.6: Added support for mongodb+srv:// URIs.Added the retryWrites keyword argument and URI option.

Changed in version 3.5: Add username and password options. Document theauthSource, authMechanism, and authMechanismProperties options. Deprecated thesocketKeepAlive keyword argument and URI option.socketKeepAlive now defaults to True.

Changed in version 3.0: MongoClient is now the one and onlyclient class for a standalone server, mongos, or replica set.It includes the functionality that had been split intoMongoReplicaSetClient: it can connectto a replica set, discover all its members, and monitor the set forstepdowns, elections, and reconfigs.

The MongoClient constructor nolonger blocks while connecting to the server or servers, and it nolonger raises ConnectionFailure if theyare unavailable, nor ConfigurationErrorif the user’s credentials are wrong. Instead, the constructorreturns immediately and launches the connection process onbackground threads.

Therefore the alive method is removed since it no longerprovides meaningful information; even if the client is disconnected,it may discover a server in time to fulfill the next operation.

In PyMongo 2.x, MongoClient accepted a list ofstandalone MongoDB servers and used the first it could connect to:

  1. MongoClient(['host1.com:27017', 'host2.com:27017'])

A list of multiple standalones is no longer supported; if multipleservers are listed they must be members of the same replica set, ormongoses in the same sharded cluster.

The behavior for a list of mongoses is changed from “highavailability” to “load balancing”. Before, the client connected tothe lowest-latency mongos in the list, and used it until a networkerror prompted it to re-evaluate all mongoses’ latencies andreconnect to one of them. In PyMongo 3, the client monitors itsnetwork latency to all the mongoses continuously, and distributesoperations evenly among those with the lowest latency. Seemongos Load Balancing for more information.

The connect option is added.

The start_request, in_request, and end_request methodsare removed, as well as the auto_start_request option.

The copy_database method is removed, see thecopy_database examples for alternatives.

The MongoClient.disconnect() method is removed; it was asynonym for close().

MongoClient no longer returns aninstance of Database for attribute nameswith leading underscores. You must use dict-style lookups instead:

  1. client['__my_database__']

Not:

  1. client.__my_database__
  • close()
  • Cleanup client resources and disconnect from MongoDB.

On MongoDB >= 3.6, end all server sessions created by this client bysending one or more endSessions commands.

Close all sockets in the connection pools and stop the monitor threads.If this instance is used again it will be automatically re-opened andthe threads restarted unless auto encryption is enabled. A clientenabled with auto encryption cannot be used again after being closed;any attempt will raise InvalidOperation.

Changed in version 3.6: End all server sessions created by this client.

Raises InvalidName if an invalid database name is used.

  • event_listeners
  • The event listeners registered for this client.

See monitoring for details.

  • address
  • (host, port) of the current standalone, primary, or mongos, or None.

Accessing address raises InvalidOperation ifthe client is load-balancing among mongoses, since there is no singleaddress. Use nodes instead.

If the client is not connected, this will block until a connection isestablished or raise ServerSelectionTimeoutError if no server isavailable.

New in version 3.0.

  • primary
  • The (host, port) of the current primary of the replica set.

Returns None if this client is not connected to a replica set,there is no primary, or this client was created without thereplicaSet option.

New in version 3.0: MongoClient gained this property in version 3.0 whenMongoReplicaSetClient’s functionality was merged in.

  • secondaries
  • The secondary members known to this client.

A sequence of (host, port) pairs. Empty if this client is notconnected to a replica set, there are no visible secondaries, or thisclient was created without the replicaSet option.

New in version 3.0: MongoClient gained this property in version 3.0 whenMongoReplicaSetClient’s functionality was merged in.

  • arbiters
  • Arbiters in the replica set.

A sequence of (host, port) pairs. Empty if this client is notconnected to a replica set, there are no arbiters, or this client wascreated without the replicaSet option.

  • is_primary
  • If this client is connected to a server that can accept writes.

True if the current server is a standalone, mongos, or the primary ofa replica set. If the client is not connected, this will block until aconnection is established or raise ServerSelectionTimeoutError if noserver is available.

  • is_mongos
  • If this client is connected to mongos. If the client is notconnected, this will block until a connection is established or raiseServerSelectionTimeoutError if no server is available..

  • max_pool_size

  • The maximum allowable number of concurrent connections to eachconnected server. Requests to a server will block if there aremaxPoolSize outstanding connections to the requested server.Defaults to 100. Cannot be 0.

When a server’s pool has reached max_pool_size, operations for thatserver block waiting for a socket to be returned to the pool. IfwaitQueueTimeoutMS is set, a blocked operation will raiseConnectionFailure after a timeout.By default waitQueueTimeoutMS is not set.

  • min_pool_size
  • The minimum required number of concurrent connections that the poolwill maintain to each connected server. Default is 0.

  • max_idle_time_ms

  • The maximum number of milliseconds that a connection can remainidle in the pool before being removed and replaced. Defaults toNone (no limit).

  • nodes

  • Set of all currently connected servers.

Warning

When connected to a replica set the value of nodescan change over time as MongoClient’s view of the replicaset changes. nodes can also be an empty set whenMongoClient is first instantiated and hasn’t yet connectedto any servers, or a network partition causes it to lose connectionto all servers.

  • max_bson_size
  • The largest BSON object the connected server accepts in bytes.

If the client is not connected, this will block until a connection isestablished or raise ServerSelectionTimeoutError if no server isavailable.

  • max_message_size
  • The largest message the connected server accepts in bytes.

If the client is not connected, this will block until a connection isestablished or raise ServerSelectionTimeoutError if no server isavailable.

  • max_write_batch_size
  • The maxWriteBatchSize reported by the server.

If the client is not connected, this will block until a connection isestablished or raise ServerSelectionTimeoutError if no server isavailable.

Returns a default value when connected to server versions prior toMongoDB 2.6.

  • local_threshold_ms
  • The local threshold for this instance.

  • server_selection_timeout

  • The server selection timeout for this instance in seconds.

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

  • is_locked
  • Is this server locked? While locked, all write operationsare blocked, although read operations may still be allowed.Use unlock() to unlock.

  • startsession(_causal_consistency=True, default_transaction_options=None)

  • Start a logical session.

This method takes the same parameters asSessionOptions. See theclient_session module for details and examples.

Requires MongoDB 3.6. It is an error to call start_session()if this client has been authenticated to multiple databases using thedeprecated method authenticate().

A ClientSession may only be used withthe MongoClient that started it.

Returns:An instance of ClientSession.

New in version 3.6.

  • listdatabases(_session=None, **kwargs)
  • Get a cursor over the databases of the connected server.

Parameters:

  1. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).
  2. - _**kwargs_ (optional): Optional parameters of the[listDatabases command](https://docs.mongodb.com/manual/reference/command/listDatabases/)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.

  • listdatabase_names(_session=None)
  • Get a list of the names of all databases on the connected server.

Parameters:

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

New in version 3.6.

  • databasenames(_session=None)
  • DEPRECATED: Get a list of the names of all databases on theconnected server.

Parameters:

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

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

Changed in version 3.6: Added session parameter.

  • dropdatabase(_name_or_database, session=None)
  • Drop a database.

Raises TypeError if name_or_database is not an instance ofbasestring (str in python 3) orDatabase.

Parameters:

  1. - _name_or_database_: the name of a database to drop, or a[<code>Database</code>]($beafcb5a2a9633e8.md#pymongo.database.Database) instance representing thedatabase to drop
  2. - _session_ (optional): a[<code>ClientSession</code>]($9cd063bf36ed4635.md#pymongo.client_session.ClientSession).

Changed in version 3.6: Added session parameter.

Note

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

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

  • getdefault_database(_default=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None)
  • Get the database named in the MongoDB connection URI.
  1. >>> uri = 'mongodb://host/my_database'
  2. >>> client = MongoClient(uri)
  3. >>> db = client.get_default_database()
  4. >>> assert db.name == 'my_database'
  5. >>> db = client.get_database()
  6. >>> assert db.name == 'my_database'

Useful in scripts where you want to choose which database to usebased only on the URI in a configuration file.

Parameters:

  1. - _default_ (optional): the database name to use if no database namewas provided in the URI.
  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.mongo_client.MongoClient.codec_options) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.read_preference) of this[<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.write_concern) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.read_concern) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) isused.

Changed in version 3.8: Undeprecated. Added the default, codec_options,read_preference, write_concern and read_concernparameters.

Changed in version 3.5: Deprecated, use get_database() instead.

  • getdatabase(_name=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None)
  • Get a Database with the given name andoptions.

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

  1. >>> client.read_preference
  2. Primary()
  3. >>> db1 = client.test
  4. >>> db1.read_preference
  5. Primary()
  6. >>> from pymongo import ReadPreference
  7. >>> db2 = client.get_database(
  8. ... 'test', read_preference=ReadPreference.SECONDARY)
  9. >>> db2.read_preference
  10. Secondary(tag_sets=None)

Parameters:

  1. - _name_ (optional): The name of the database - a string. If <code>None</code>(the default) the database named in the MongoDB connection URI isreturned.
  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.mongo_client.MongoClient.codec_options) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.read_preference) of this[<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.write_concern) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) 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.mongo_client.MongoClient.read_concern) of this [<code>MongoClient</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.mongo_client.MongoClient) isused.

Changed in version 3.5: The name parameter is now optional, defaulting to the databasenamed in the MongoDB connection URI.

  • serverinfo(_session=None)
  • Get information about the MongoDB server we’re connected to.

Parameters:

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

Changed in version 3.6: Added session parameter.

  • closecursor(_cursor_id, address=None)
  • DEPRECATED - Send a kill cursors message soon with the given id.

Raises TypeError if cursor_id is not an instance of(int, long). What closing the cursor actually meansdepends on this client’s cursor manager.

This method may be called from a Cursordestructor during garbage collection, so it isn’t safe to take alock or do network I/O. Instead, we schedule the cursor to be closedsoon on a background thread.

Parameters:

  1. - _cursor_id_: id of cursor to close
  2. - _address_ (optional): (host, port) pair of the cursors server.If it is not provided, the client attempts to close the cursor onthe primary or standalone, or a mongos server.

Changed in version 3.7: Deprecated.

Changed in version 3.0: Added address parameter.

  • killcursors(_cursor_ids, address=None)
  • DEPRECATED - Send a kill cursors message soon with the given ids.

Raises TypeError if cursor_ids is not an instance oflist.

Parameters:

  1. - _cursor_ids_: list of cursor ids to kill
  2. - _address_ (optional): (host, port) pair of the cursors server.If it is not provided, the client attempts to close the cursor onthe primary or standalone, or a mongos server.

Changed in version 3.3: Deprecated.

Changed in version 3.0: Now accepts an address argument. Schedules the cursors to beclosed on a background thread instead of sending the messageimmediately.

  • setcursor_manager(_manager_class)
  • DEPRECATED - Set this client’s cursor manager.

Raises TypeError if manager_class is not a subclass ofCursorManager. A cursor managerhandles closing cursors. Different managers can implement differentpolicies in terms of when to actually kill a cursor that hasbeen closed.

Parameters:

  1. - _manager_class_: cursor manager to use

Changed in version 3.3: Deprecated, for real this time.

Changed in version 3.0: Undeprecated.

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

Performs an aggregation with an implicit initial $changeStreamstage and returns aClusterChangeStream cursor whichiterates over changes on all databases on this cluster.

Introduced in MongoDB 4.0.

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

The ClusterChangeStream 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 client.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 ClusterChangeStream cursor.

Changed in version 3.9: Added the start_after parameter.

New in version 3.7.

See also

The MongoDB documentation on

changeStreams

  • fsync(**kwargs)
  • Flush all pending writes to datafiles.

    • Optional parameters can be passed as keyword arguments:
      • lock: If True lock the server to disallow writes.
      • async: If True don’t block while synchronizing.
      • session (optional): aClientSession.

Note

Starting with Python 3.7 async is a reserved keyword.The async option to the fsync command can be passed using adictionary instead:

  1. options = {'async': True}
  2. client.fsync(**options)

Changed in version 3.6: Added session parameter.

Warning

async and lock can not be used together.

Warning

MongoDB does not support the async optionon Windows and will raise an exception on thatplatform.

  • unlock(session=None)
  • Unlock a previously locked server.

Parameters:

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

Changed in version 3.6: Added session parameter.