Tools for connecting to a MongoDB replica set.
See also
High Availability and PyMongo for more examples of how to connect to a replica set.
To get a Database instance from a MongoReplicaSetClient use either dictionary-style or attribute-style access:
>>> from pymongo import MongoReplicaSetClient
>>> c = MongoReplicaSetClient('localhost:27017', replicaSet='repl0')
>>> c.test_database
Database(MongoReplicaSetClient([u'...', u'...']), u'test_database')
>>> c['test_database']
Database(MongoReplicaSetClient([u'...', u'...']), u'test_database')
Create a new connection to a MongoDB replica set.
The resultant client object has connection-pooling built in. It also performs auto-reconnection when necessary. If an operation fails because of a connection error, ConnectionFailure is raised. If auto-reconnection will be performed, AutoReconnect will be raised. Application code should handle this exception (recognizing that the operation failed) and then continue to execute.
Raises ConnectionFailure if the connection cannot be made.
The hosts_or_uri parameter can be a full mongodb URI, in addition to a string of host:port pairs (e.g. ‘host1:port1,host2:port2’). If hosts_or_uri is None ‘localhost:27017’ will be used.
Note
Instances of MongoReplicaSetClient start a background task to monitor the state of the replica set. This allows it to quickly respond to changes in replica set configuration. Before discarding an instance of MongoReplicaSetClient make sure you call close() to ensure that the monitor task is cleanly shut down.
Parameters: |
Other optional parameters can be passed as keyword arguments:
Write Concern options:
Read preference options:
SSL configuration:
|
---|
Changed in version 2.5: Added additional ssl options
New in version 2.4.
Disconnect from the replica set primary, unpin all members, and refresh our view of the replica set.
Close this client instance.
This method first terminates the replica set monitor, then disconnects from all members of the replica set. No further operations are permitted on this client.
Warning
This method stops the replica set monitor task. The replica set monitor is required to properly handle replica set configuration changes, including a failure of the primary. Once close() is called this client instance must not be reused.
Changed in version 2.2.1: The close() method now terminates the replica set monitor.
Return False if there has been an error communicating with the primary, else True.
This method attempts to check the status of the primary with minimal I/O. The current thread / greenlet retrieves a socket (its request socket if it’s in a request, or a random idle socket if it’s not in a request) from the primary’s connection pool and checks whether calling select on it raises an error. If there are currently no idle sockets, alive() attempts to connect a new socket.
A more certain way to determine primary availability is to ping it:
client.admin.command('ping')
Get the db_name Database on MongoReplicaSetClient c.
Raises InvalidName if an invalid database name is used.
The seed list used to connect to this replica set.
A sequence of (host, port) pairs.
All active and passive (priority 0) replica set members known to this client. This does not include hidden or slaveDelay members, or arbiters.
A sequence of (host, port) pairs.
The (host, port) of the current primary of the replica set.
Returns None if there is no primary.
The secondary members known to this client.
A sequence of (host, port) pairs.
The arbiters known to this client.
A sequence of (host, port) pairs.
If this instance is connected to mongos (always False).
New in version 2.3.
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.
Warning
SIGNIFICANT BEHAVIOR CHANGE in 2.6. Previously, this parameter would limit only the idle sockets the pool would hold onto, not the number of open sockets. The default has also changed to 100.
Changed in version 2.6.
Default class to use for documents returned from this client.
Does this client return timezone-aware datetimes?
Returns the maximum size BSON object the connected primary accepts in bytes. Defaults to 16MB if not connected to a primary.
Returns the maximum message size the connected primary accepts in bytes. Defaults to 32MB if not connected to a primary.
The minWireVersion reported by the server.
Returns 0 when connected to server versions prior to MongoDB 2.6.
New in version 2.7.
The maxWireVersion reported by the server.
Returns 0 when connected to server versions prior to MongoDB 2.6.
New in version 2.7.
Is auto_start_request enabled?
The read preference mode for this instance.
See ReadPreference for available options.
New in version 2.1.
Set tag_sets to a list of dictionaries like [{‘dc’: ‘ny’}] to read only from members whose dc tag has the value "ny". To specify a priority-order for tag sets, provide a list of tag sets: [{'dc': 'ny'}, {'dc': 'la'}, {}]. A final, empty tag set, {}, means “read from any member that matches the mode, ignoring tags.” ReplicaSetConnection tries each set of tags in turn until it finds a set of tags with at least one matching member.
See also
New in version 2.3.
Any replica-set member whose ping time is within secondary_acceptable_latency_ms of the nearest member may accept reads. Defaults to 15 milliseconds.
See ReadPreference.
New in version 2.3.
Note
secondary_acceptable_latency_ms is ignored when talking to a replica set through a mongos. The equivalent is the localThreshold command line option.
The default write concern for this instance.
Supports dict style access for getting/setting write concern options. Valid options include:
>>> m = pymongo.MongoClient()
>>> m.write_concern
{}
>>> m.write_concern = {'w': 2, 'wtimeout': 1000}
>>> m.write_concern
{'wtimeout': 1000, 'w': 2}
>>> m.write_concern['j'] = True
>>> m.write_concern
{'wtimeout': 1000, 'j': True, 'w': 2}
>>> m.write_concern = {'j': True}
>>> m.write_concern
{'j': True}
>>> # Disable write acknowledgement and write concern
...
>>> m.write_concern['w'] = 0
Note
Accessing write_concern returns its value (a subclass of dict), not a copy.
Warning
If you are using Connection or ReplicaSetConnection make sure you explicitly set w to 1 (or a greater value) or safe to True. Unlike calling set_lasterror_options(), setting an option in write_concern does not implicitly set safe to True.
This attribute specifies which BSON Binary subtype is used when storing UUIDs. Historically UUIDs have been stored as BSON Binary subtype 3. This attribute is used to switch to the newer BSON Binary subtype 4. It can also be used to force legacy byte order and subtype compatibility with the Java and C# drivers. See the bson.binary module for all options.
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: |
|
---|
Copy a database, potentially from another host.
Raises TypeError if from_name or to_name is not an instance of basestring (str in python 3). Raises InvalidName if to_name is not a valid database name.
If from_host is None the current host is used as the source. Otherwise the database is copied from from_host.
If the source database requires authentication, username and password must be specified.
Parameters: |
|
---|
Note
Specifying username and password requires server version >= 1.3.3+.
Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoReplicaSetClient(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.
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.
Parameters: |
|
---|