MotorClient – Connection to MongoDB

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

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

MotorClient takes the same constructor arguments as MongoClient, as well as:

Parameters:
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(*args, **kwargs)

Copy a database, potentially from another host.

Accepts an optional callback, or returns a Future.

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 parameters (response, error)
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.

get_default_database()

Get the database named in the MongoDB connection URI.

>>> uri = 'mongodb://localhost/my_database'
>>> client = MotorClient(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.

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(*args, **kwargs)

Connect to the server.

Takes an optional callback, or returns a Future that resolves to self when opened. This is convenient for checking at program startup time whether you can connect.

>>> client = MotorClient()
>>> # run_sync() returns the open client.
>>> IOLoop.current().run_sync(client.open)
MotorClient(MongoClient('localhost', 27017))

open raises a ConnectionFailure if it cannot connect, but note that auth failures aren’t revealed until you attempt an operation on the open client.

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

Changed in version 0.2: MotorClient now opens itself on demand, calling open explicitly is now optional.

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.

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.

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 16MB if not connected to a server.

max_message_size

Return the maximum message size the connected server accepts in bytes. Defaults to 32MB if not connected to a server.

max_pool_size

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.

max_wire_version

The maxWireVersion reported by the server.

Returns 0 when connected to server versions prior to MongoDB 2.6.

min_wire_version

The minWireVersion reported by the server.

Returns 0 when connected to server versions prior to MongoDB 2.6.

nodes

List of all known nodes.

Nodes are either specified when this instance was created, or 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. Cannot be used in combination with fsync. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling.
  • fsync: If True and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the j option, blocking until write operations have been committed to the journal. Cannot be used in combination with j.
>>> 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.