MotorClient – Connection to MongoDB

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

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

Takes the same constructor arguments as MongoClient, as well as:

Parameters:
client[db_name] || client.db_name

Get the db_name MotorDatabase on MotorClient client.

Raises InvalidName if an invalid database name is used.

coroutine close_cursor(cursor_id, address=None, callback=None)

Send a kill cursors message soon with the given id.

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.

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.

Parameters:
  • cursor_id: id of cursor to close
  • address (optional): (host, port) pair of the cursor’s server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server.
  • callback (optional): function taking (result, error), executed when operation completes

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

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

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

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

coroutine 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

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

Note

The write_concern of this client is automatically applied to this operation when using MongoDB >= 3.4.

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

coroutine fsync(callback=None, **kwargs)

Flush all pending writes to datafiles.

Parameters:

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

Optional parameters can be passed as keyword arguments:

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

  • lock: If True lock the server to disallow writes.
  • async: If True don’t block while synchronizing.

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_database(name, codec_options=None, read_preference=None, write_concern=None, read_concern=None)

Get a MotorDatabase with the given name and options.

Useful for creating a MotorDatabase with different codec options, read preference, and/or write concern from this MotorClient.

>>> from pymongo import ReadPreference
>>> client.read_preference == ReadPreference.PRIMARY
True
>>> db1 = client.test
>>> db1.read_preference == ReadPreference.PRIMARY
True
>>> db2 = client.get_database(
...     'test', read_preference=ReadPreference.SECONDARY)
>>> db2.read_preference == ReadPreference.SECONDARY
True
Parameters:
  • name: The name of the database - a string.
  • codec_options (optional): An instance of CodecOptions. If None (the default) the codec_options of this MongoClient is used.
  • read_preference (optional): The read preference to use. If None (the default) the read_preference of this MongoClient is used. See read_preferences for options.
  • write_concern (optional): An instance of WriteConcern. If None (the default) the write_concern of this MongoClient is used.
get_default_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.

coroutine kill_cursors(cursor_ids, address=None, callback=None)

DEPRECATED - Send a kill cursors message soon with the given ids.

Raises TypeError if cursor_ids is not an instance of list.

Parameters:
  • cursor_ids: list of cursor ids to kill
  • address (optional): (host, port) pair of the cursor’s server. If it is not provided, the client attempts to close the cursor on the primary or standalone, or a mongos server.
  • callback (optional): function taking (result, error), executed when operation completes

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

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

coroutine server_info(callback=None)

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

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

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

coroutine unlock(callback=None)

Unlock a previously locked server.

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

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

HOST

str(object=’‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

PORT

int(x=0) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

address

(host, port) of the current standalone, primary, or mongos, or None.

Accessing address raises InvalidOperation if the client is load-balancing among mongoses, since there is no single address. Use nodes instead.

If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

New in version 3.0.

arbiters

Arbiters in the replica set.

A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no arbiters, or this client was created without the replicaSet option.

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.

codec_options

Read only access to the CodecOptions of this instance.

event_listeners

The event listeners registered for this client.

See monitoring for details.

is_mongos

If this client is connected to mongos. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available..

is_primary

If this client is 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 the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

local_threshold_ms

The local threshold for this instance.

max_bson_size

The largest BSON object the connected server accepts in bytes.

If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

max_idle_time_ms

The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to None (no limit).

max_message_size

The largest message the connected server accepts in bytes.

If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

max_pool_size

The maximum allowable number of concurrent connections to each connected server. Requests to a server will block if there are maxPoolSize outstanding connections to the requested server. Defaults to 100. Cannot be 0.

When a server’s pool has reached max_pool_size, operations for that server 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.

max_write_batch_size

The maxWriteBatchSize reported by the server.

If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available.

Returns a default value when connected to server versions prior to MongoDB 2.6.

min_pool_size

The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.

nodes

Set of all currently connected servers.

Warning

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.

primary

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

Returns None if this client is not connected to a replica set, there is no primary, or this client was created without the replicaSet option.

New in version 3.0: MongoClient gained this property in version 3.0 when MongoReplicaSetClient’s functionality was merged in.

read_concern

Read only access to the read concern of this instance.

New in version 3.2.

read_preference

Read only access to the read preference of this instance.

Changed in version 3.0: The read_preference attribute is now read only.

secondaries

The secondary members known to this client.

A sequence of (host, port) pairs. Empty if this client is not connected to a replica set, there are no visible secondaries, or this client was created without the replicaSet option.

New in version 3.0: MongoClient gained this property in version 3.0 when MongoReplicaSetClient’s functionality was merged in.

server_selection_timeout

The server selection timeout for this instance in seconds.

write_concern

Read only access to the WriteConcern of this instance.

Changed in version 3.0: The write_concern attribute is now read only.