MotorClient – Connection to MongoDB

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

Create a new connection to a single MongoDB instance at host:port.

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

MotorClient takes the same constructor arguments as MongoClient, 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.
disconnect()

Disconnect from MongoDB.

Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened. Care should be taken to make sure that disconnect() is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results.

See also

end_request()

client[db_name] || client.db_name

Get the db_name MotorDatabase on MotorClient 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 server, else True.

This method attempts to check the status of the server with minimal I/O. The current thread / greenlet retrieves a socket from the pool (its request socket if it’s in a request, or a random idle socket if it’s not in a request) and checks whether calling select on it raises an error. If there are currently no idle sockets, alive() will attempt to actually connect to the server.

A more certain way to determine server availability is:

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()

Alias for disconnect()

Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened. Care should be taken to make sure that disconnect() is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results.

See also

end_request()

close_cursor(cursor_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 MongoDB.

Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened. Care should be taken to make sure that disconnect() is not called in the middle of a sequence of operations in which ordering is important. This could lead to unexpected results.

See also

end_request()

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.

fsync(callback=None, **kwargs)

Flush all pending writes to datafiles.

Parameters :

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.
  • callback (optional): function taking (result, error), executed when operation completes

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.

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

kill_cursors(cursor_ids, callback=None)

Send a kill cursors message with the given ids.

Raises TypeError if cursor_ids is not an instance of list.

Parameters :
  • cursor_ids: list of cursor ids to kill
  • callback (optional): function taking (result, error), executed when operation completes

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

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

sync_client()

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

unlock(callback=None)

Unlock a previously locked server.

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

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

connected

True after open() or open_sync() completes

document_class

Default class to use for documents returned from this client.

host

Current connected host.

is_mongos

If this instance is connected to mongos.

is_primary

If this instance is connected to a standalone, a replica set primary, or the master of a master-slave set.

max_bson_size

Return the maximum size BSON object the connected server accepts in bytes. Defaults to 4MB in server < 1.7.4.

max_pool_size

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

Note

max_pool_size does not cap the number of concurrent connections to the server; 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 the pool.

nodes

List of all known nodes.

Includes both nodes specified when this instance was created, as well as nodes discovered through the replica set discovery mechanism.

port

Current connected port.

read_preference

The read preference mode for this instance.

See ReadPreference for available options.

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.

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

Motor API

Next topic

MotorReplicaSetClient – Connection to MongoDB replica set

This Page