MotorReplicaSetClient – Connection to MongoDB replica set

class motor.MotorReplicaSetClient(*args, **kwargs)

Create a new connection to a MongoDB replica set.

open() or open_sync() must be called before using a new MotorReplicaSetClient. No property access is allowed before the connection is opened.

MotorReplicaSetClient takes the same constructor arguments as MongoReplicaSetClient, as well as:

Parameters :
  • io_loop (optional): Special tornado.ioloop.IOLoop instance to use instead of default
  • max_concurrent (optional): Most connections open at once, default 100.
  • max_wait_time (optional): How long an operation can wait for a connection before raising MotorPoolTimeout, default no timeout.
client[db_name] || client.db_name

Get the db_name MotorDatabase on MotorReplicaSetClient client.

Raises InvalidName if an invalid database name is used. Raises InvalidOperation if connection isn’t opened yet.

alive(callback=None)

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, or if there is no known primary, alive() will attempt to actually find and connect to the primary.

A more certain way to determine primary availability is to ping it:

client.admin.command('ping')
Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

close()

Close this client instance.

This method first terminates the replica set monitor, then disconnects from all members of the replica set.

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.

close_cursor(cursor_id, _conn_id, callback=None)

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 :
  • cursor_id: id of cursor to close
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

copy_database(from_name, to_name, from_host=None, username=None, password=None, callback=None)

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 :
  • from_name: the name of the source database
  • to_name: the name of the target database
  • from_host (optional): host name to copy from
  • username (optional): username for source database
  • password (optional): password for source database
  • callback (optional): function taking (result, error), executed when operation completes

Note

Specifying username and password requires server version >= 1.3.3+.

If a callback is passed, returns None, else returns a Future.

database_names(callback=None)

Get a list of the names of all databases on the connected server.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

disconnect()

Disconnect from the replica set primary, unpin all members, and refresh our view of the replica set.

drop_database(name_or_database, callback=None)

Drop a database.

Raises TypeError if name_or_database is not an instance of basestring (str in python 3) or Database

Parameters :
  • name_or_database: the name of a database to drop, or a Database instance representing the database to drop
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

get_document_class()

document_class getter

open(callback=None)

Actually initialize. Takes an optional callback, or returns a Future that resolves to self when opened.

Parameters :
  • callback: Optional function taking parameters (self, error)
open_sync()

Synchronous open(), returning self.

Under the hood, this method creates a new Tornado IOLoop, runs open() on the loop, and deletes the loop when open() completes.

server_info(callback=None)

Get information about the MongoDB primary we’re connected to.

Parameters :
  • callback (optional): function taking (result, error), executed when operation completes

If a callback is passed, returns None, else returns a Future.

set_document_class(klass)

document_class setter

sync_client()

Get a PyMongo MongoClient / MongoReplicaSetClient with the same configuration as this MotorClient / MotorReplicaSetClient.

arbiters

The arbiters known to this client.

A sequence of (host, port) pairs.

connected

True after open() or open_sync() completes

document_class

Default class to use for documents returned from this client.

hosts

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.

is_mongos

If this instance is connected to mongos (always False).

max_bson_size

Returns the maximum size BSON object the connected primary accepts in bytes. Defaults to 4MB in server < 1.7.4. Returns 0 if no primary is available.

max_pool_size

The maximum number of idle connections kept open in each pool for future use.

Note

max_pool_size does not cap the number of concurrent connections to a replica set member; there is currently no way to limit the number of connections. max_pool_size only limits the number of idle connections kept open when they are returned to a pool.

primary

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

Returns None if there is no primary.

read_preference

The read preference mode for this instance.

See ReadPreference for available options.

secondaries

The secondary members known to this client.

A sequence of (host, port) pairs.

secondary_acceptable_latency_ms

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.

Note

secondary_acceptable_latency_ms is ignored when talking to a replica set through a mongos. The equivalent is the localThreshold command line option.

seeds

The seed list used to connect to this replica set.

A sequence of (host, port) pairs.

tag_sets

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.

tz_aware

Does this client return timezone-aware datetimes?

write_concern

The default write concern for this instance.

Supports dict style access for getting/setting write concern options. Valid options include:

  • w: (integer or string) If this is a replica set, write operations will block until they have been replicated to the specified number or tagged set of servers. w=<int> always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to two secondaries). Setting w=0 disables write acknowledgement and all other write concern options.
  • wtimeout: (integer) Used in conjunction with w. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised.
  • j: If True block until write operations have been committed to the journal. Ignored if the server is running without journaling.
  • fsync: If True force the database to fsync all files before returning. When used with j the server awaits the next group commit before returning.
>>> 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.

Previous topic

MotorClient – Connection to MongoDB

Next topic

MotorDatabase

This Page