Tools for connecting to MongoDB.
High Availability and PyMongo for examples of connecting to replica sets or sets of mongos servers.
>>> from pymongo import MongoClient >>> c = MongoClient() >>> c.test_database Database(MongoClient('localhost', 27017), u'test_database') >>> c['test-database'] Database(MongoClient('localhost', 27017), 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 escaped following RFC 2396.
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:
See general MongoDB documentation
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:
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().
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.
Raises InvalidName if an invalid database name is used.
(host, port) of the current standalone, primary, or mongos, or None.
New in version 3.0.
If this client if 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 this client is connected to mongos.
The maximum number of sockets the pool will open concurrently.
When the pool has reached max_pool_size, operations 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.
Set of all currently connected servers.
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.
Defaults to 16MB if not connected to a server.
The largest message the connected server accepts in bytes.
Defaults to 32MB if not connected to a server.
The local threshold for 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.
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.
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'
Useful in scripts where you want to choose which database to use based only on the URI in a configuration file.
Get a Database with the given name and options.
>>> 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)
Get information about the MongoDB server we’re connected to.
Close a single database cursor.
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.
Changed in version 3.0: Added address parameter.
Send a kill cursors message soon with the given ids.
Raises TypeError if cursor_ids is not an instance of list.
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.
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.
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.
Changed in version 3.0: Undeprecated.
Flush all pending writes to datafiles.
Optional parameters can be passed as keyword arguments:
async and lock can not be used together.
MongoDB does not support the async option on Windows and will raise an exception on that platform.
Unlock a previously locked server.