Tools for connecting to MongoDB.
See also
High Availability and PyMongo for examples of connecting to replica sets or sets of mongos servers.
To get a Database instance from a MongoClient use either dictionary-style or attribute-style access:
>>> from pymongo import MongoClient
>>> c = MongoClient()
>>> c.test_database
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test_database')
>>> c['test-database']
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'test-database')
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 client reconnects in the background. Application code should handle this exception (recognizing that the operation failed) and then continue to execute.
The host parameter can be a full mongodb URI, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the port parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ‘:’, ‘/’, ‘+’ and ‘@’ must be percent encoded following RFC 2396:
try:
# Python 3.x
from urllib.parse import quote_plus
except ImportError:
# Python 2.x
from urllib import quote_plus
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), host)
client = MongoClient(uri)
Unix domain sockets are also supported. The socket path must be percent encoded in the URI:
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), quote_plus(socket_path))
client = MongoClient(uri)
But not when passed as a simple hostname:
client = MongoClient('/tmp/mongodb-27017.sock')
Note
Starting with version 3.0 the MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads. You can check if the server is available like this:
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
Warning
When using PyMongo in a multiprocessing context, please read Using PyMongo with Multiprocessing first.
Parameters: |
Other optional parameters can be passed as keyword arguments:
Write Concern options:
(Only set if passed. No default values.)
Replica set keyword arguments for connecting with a replica set
- either directly or via a mongos:
Read Preference:
Authentication:
See also SSL configuration:
Read Concern options:
(If not set explicitly, this will use the server default)
|
---|
Changed in version 3.5: Add username and password options. Document the authSource, authMechanism, and authMechanismProperties `` options. Deprecated the `socketKeepAlive` keyword argument and URI option. `socketKeepAlive` now defaults to ``True.
Changed in version 3.0: MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs.
The MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads.
Therefore the alive method is removed since it no longer provides 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 of standalone MongoDB servers and used the first it could connect to:
MongoClient(['host1.com:27017', 'host2.com:27017'])
A list of multiple standalones is no longer supported; if multiple servers are listed they must be members of the same replica set, or mongoses in the same sharded cluster.
The behavior for a list of mongoses is changed from “high availability” to “load balancing”. Before, the client connected to the lowest-latency mongos in the list, and used it until a network error prompted it to re-evaluate all mongoses’ latencies and reconnect to one of them. In PyMongo 3, the client monitors its network latency to all the mongoses continuously, and distributes operations evenly among those with the lowest latency. See mongos Load Balancing for more information.
The connect option is added.
The start_request, in_request, and end_request methods are removed, as well as the auto_start_request option.
The copy_database method is removed, see the copy_database examples for alternatives.
The MongoClient.disconnect() method is removed; it was a synonym for close().
MongoClient no longer returns an instance of Database for attribute names with leading underscores. You must use dict-style lookups instead:
client['__my_database__']
Not:
client.__my_database__
Disconnect from MongoDB.
Close all sockets in the connection pools and stop the monitor threads. If this instance is used again it will be automatically re-opened and the threads restarted.
Get the db_name Database on MongoClient c.
Raises InvalidName if an invalid database name is used.
The event listeners registered for this client.
See monitoring for details.
(host, port) of the current standalone, primary, or mongos, or None.
Accessing address raises InvalidOperation if the client is load-balancing among mongoses, since there is no single address. Use nodes instead.
If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.
New in version 3.0.
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 the replicaSet option.
New in version 3.0: MongoClient gained this property in version 3.0 when MongoReplicaSetClient’s functionality was merged in.
The secondary members known to this client.
A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the replicaSet option.
New in version 3.0: MongoClient gained this property in version 3.0 when MongoReplicaSetClient’s functionality was merged in.
Arbiters in the replica set.
A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the replicaSet option.
If this client is connected to a server that can accept writes.
True if the current server is a standalone, mongos, or the primary of a replica set. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.
If this client is connected to mongos. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available..
The maximum allowable number of concurrent connections to each connected server. Requests to a server will block if there are maxPoolSize outstanding connections to the requested server. Defaults to 100. Cannot be 0.
When a server’s pool has reached max_pool_size, operations for that server block waiting for a socket to be returned to the pool. If waitQueueTimeoutMS is set, a blocked operation will raise ConnectionFailure after a timeout. By default waitQueueTimeoutMS is not set.
The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.
The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to None (no limit).
Set of all currently connected servers.
Warning
When connected to a replica set the value of nodes can change over time as MongoClient‘s view of the replica set changes. nodes can also be an empty set when MongoClient is first instantiated and hasn’t yet connected to any servers, or a network partition causes it to lose connection to all servers.
The largest BSON object the connected server accepts in bytes.
If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.
The largest message the connected server accepts in bytes.
If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.
The maxWriteBatchSize reported by the server.
If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.
Returns a default value when connected to server versions prior to MongoDB 2.6.
The local threshold for this instance.
The server selection timeout for this instance in seconds.
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.
Read only access to the WriteConcern of this instance.
Changed in version 3.0: The write_concern attribute is now read only.
Read only access to the read concern of this instance.
New in version 3.2.
Is this server locked? While locked, all write operations are blocked, although read operations may still be allowed. Use unlock() to unlock.
Get a list of the names of all databases on the connected server.
Drop a database.
Raises TypeError if name_or_database is not an instance of basestring (str in python 3) or Database.
Parameters: |
|
---|
Note
The write_concern of this client is automatically applied to this operation when using MongoDB >= 3.4.
Changed in version 3.4: Apply this client’s write concern automatically to this operation when connected to MongoDB >= 3.4.
Get a Database with the given name and options.
Useful for creating a Database with different codec options, read preference, and/or write concern from this MongoClient.
>>> client.read_preference
Primary()
>>> db1 = client.test
>>> db1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> db2 = client.get_database(
... 'test', read_preference=ReadPreference.SECONDARY)
>>> db2.read_preference
Secondary(tag_sets=None)
Parameters: |
|
---|
Changed in version 3.5: The name parameter is now optional, defaulting to the database named in the MongoDB connection URI.
Get information about the MongoDB server we’re connected to.
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 means depends on this client’s cursor manager.
This method may be called from a Cursor destructor during garbage collection, so it isn’t safe to take a lock or do network I/O. Instead, we schedule the cursor to be closed soon on a background thread.
Parameters: |
|
---|
Changed in version 3.0: Added address parameter.
DEPRECATED - Send a kill cursors message soon with the given ids.
Raises TypeError if cursor_ids is not an instance of list.
Parameters: |
|
---|
Changed in version 3.3: Deprecated.
Changed in version 3.0: Now accepts an address argument. Schedules the cursors to be closed on a background thread instead of sending the message immediately.
DEPRECATED - Set this client’s cursor manager.
Raises TypeError if manager_class is not a subclass of CursorManager. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed.
Parameters: |
|
---|
Changed in version 3.3: Deprecated, for real this time.
Changed in version 3.0: Undeprecated.
Flush all pending writes to datafiles.
Parameters: | Optional parameters can be passed as keyword arguments:
Warning async and lock can not be used together. Warning MongoDB does not support the async option on Windows and will raise an exception on that platform. |
---|
Unlock a previously locked server.
DEPRECATED - Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
>>> db = client.get_database()
>>> assert db.name == 'my_database'
Useful in scripts where you want to choose which database to use based only on the URI in a configuration file.
Changed in version 3.5: Deprecated, use get_database() instead.