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: - io_loop (optional): Special
tornado.ioloop.IOLoop
instance to use instead of default
-
client[db_name] || client.db_name
Get the db_name
MotorDatabase
onMotorClient
client.Raises
InvalidName
if an invalid database name is used.
-
coroutine
close_cursor
(cursor_id, address=None, callback=None)¶ DEPRECATED - 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
If a callback is passed, returns None, else returns a Future.
-
coroutine
database_names
(session=None, callback=None)¶ DEPRECATED: Get a list of the names of all databases on the connected server.
Parameters: - session (optional): a
ClientSession
. callback
(optional): function taking (result, error), executed when operation completes
If a callback is passed, returns None, else returns a Future.
- session (optional): a
-
coroutine
drop_database
(name_or_database, session=None, callback=None)¶ Drop a database.
Raises
TypeError
if name_or_database is not an instance ofbasestring
(str
in python 3) orDatabase
.Parameters: - name_or_database: the name of a database to drop, or a
Database
instance representing the database to drop - session (optional): a
ClientSession
. 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.
- name_or_database: the name of a database to drop, or a
-
coroutine
fsync
(callback=None, **kwargs)¶ Flush all pending writes to datafiles.
- 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.
- session (optional): a
ClientSession
.
Note
Starting with Python 3.7 async is a reserved keyword. The async option to the fsync command can be passed using a dictionary instead:
options = {'async': True} client.fsync(**options)
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.
Parameters : callback
(optional): function taking (result, error), executed when operation completesIf a callback is passed, returns None, else returns a Future.
-
get_database
(name=None, 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 thisMotorClient
.>>> 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
. IfNone
(the default) thecodec_options
of thisMongoClient
is used. - read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisMongoClient
is used. Seeread_preferences
for options. - write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisMongoClient
is used.
-
get_default_database
(default=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None)¶ 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' >>> db = client.get_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.
Parameters: - default (optional): the database name to use if no database name was provided in the URI.
- codec_options (optional): An instance of
CodecOptions
. IfNone
(the default) thecodec_options
of thisMongoClient
is used. - read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisMongoClient
is used. Seeread_preferences
for options. - write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisMongoClient
is used. - read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisMongoClient
is used.
Changed in version 3.8: Undeprecated. Added the
default
,codec_options
,read_preference
,write_concern
andread_concern
parameters.Changed in version 3.5: Deprecated, use
get_database()
instead.
-
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 oflist
.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
If a callback is passed, returns None, else returns a Future.
-
coroutine
list_database_names
(session=None, callback=None)¶ Get a list of the names of all databases on the connected server.
Parameters: - session (optional): a
ClientSession
. callback
(optional): function taking (result, error), executed when operation completes
If a callback is passed, returns None, else returns a Future.
- session (optional): a
-
coroutine
list_databases
(session=None, callback=None, **kwargs)¶ Get a cursor over the databases of the connected server.
Parameters: - session (optional): a
ClientSession
. callback
(optional): function taking (result, error), executed when operation completes- **kwargs (optional): Optional parameters of the listDatabases command can be passed as keyword arguments to this method. The supported options differ by server version.
Returns: An instance of
CommandCursor
.If a callback is passed, returns None, else returns a Future.
- session (optional): a
-
coroutine
server_info
(session=None, callback=None)¶ Get information about the MongoDB server we’re connected to.
Parameters: - session (optional): a
ClientSession
. callback
(optional): function taking (result, error), executed when operation completes
If a callback is passed, returns None, else returns a Future.
- session (optional): a
-
coroutine
start_session
(causal_consistency=True, default_transaction_options=None, callback=None)¶ Start a logical session.
This method takes the same parameters as PyMongo’s
SessionOptions
. See theclient_session
module for details.async def coro(): collection = client.db.collection with (await client.start_session()) as s: doc = {'_id': ObjectId(), 'x': 1} await collection.insert_one(doc, session=s) secondary = collection.with_options( read_preference=ReadPreference.SECONDARY) # Sessions are causally consistent by default, we can read the doc # we just inserted, even reading from a secondary. async for doc in secondary.find(session=s): print(doc)
Do not use the same session for multiple operations concurrently.
Requires MongoDB 3.6. It is an error to call
start_session()
if this client has been authenticated to multiple databases using the deprecated methodauthenticate()
.A
ClientSession
may only be used with the MongoClient that started it.Returns: An instance of ClientSession
.callback
(optional): function taking (result, error), executed when operation completesNew in version 1.2.
If a callback is passed, returns None, else returns a Future.
-
coroutine
unlock
(session=None, callback=None)¶ Unlock a previously locked server.
Parameters: - session (optional): a
ClientSession
. callback
(optional): function taking (result, error), executed when operation completes
If a callback is passed, returns None, else returns a Future.
- session (optional): a
-
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]) -> 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
raisesInvalidOperation
if the client is load-balancing among mongoses, since there is no single address. Usenodes
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
¶ Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by sending one or more endSessions commands.
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 unless auto encryption is enabled. A client enabled with auto encryption cannot be used again after being closed; any attempt will raise
InvalidOperation
.Changed in version 3.6: End all server sessions created by this client.
-
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 raiseConnectionFailure
after a timeout. By defaultwaitQueueTimeoutMS
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 asMongoClient
’s view of the replica set changes.nodes
can also be an empty set whenMongoClient
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
ReadConcern
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.
-
retry_writes
¶ If this instance should retry supported write operations.
-
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.
- io_loop (optional): Special