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 event loop 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
drop_database
(name_or_database, session=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
.
Note
The
write_concern
of this client is automatically applied to this operation when using MongoDB >= 3.4.- name_or_database: the name of a database to drop, or a
-
coroutine
fsync
(**kwargs)¶ DEPRECATED: 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
, created withstart_session()
.
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} await client.fsync(**options)
Deprecated. Run the fsync command directly with
command()
instead. For example:await client.admin.command('fsync', lock=True)
Changed in version 2.2: Deprecated.
Changed in version 1.2: Added
session
parameter.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.
-
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 thisMotorClient
is used. - read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisMotorClient
is used. Seeread_preferences
for options. - write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisMotorClient
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 = MotorClient(uri) >>> db = client.get_default_database() >>> assert db.name == 'my_database' >>> db = client.get_default_database('fallback_db_name') >>> assert db.name == 'my_database' >>> uri_without_database = 'mongodb://host/' >>> client = MotorClient(uri_without_database) >>> db = client.get_default_database('fallback_db_name') >>> assert db.name == 'fallback_db_name'
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 thisMotorClient
is used. - read_preference (optional): The read preference to use. If
None
(the default) theread_preference
of thisMotorClient
is used. Seeread_preferences
for options. - write_concern (optional): An instance of
WriteConcern
. IfNone
(the default) thewrite_concern
of thisMotorClient
is used. - read_concern (optional): An instance of
ReadConcern
. IfNone
(the default) theread_concern
of thisMotorClient
is used.
New in version 2.1: Revived this method. Added the
default
,codec_options
,read_preference
,write_concern
andread_concern
parameters.Changed in version 2.0: Removed this method.
-
coroutine
list_database_names
(session=None)¶ Get a list of the names of all databases on the connected server.
Parameters: - session (optional): a
ClientSession
.
- session (optional): a
-
coroutine
list_databases
(session=None, **kwargs)¶ Get a cursor over the databases of the connected server.
Parameters: - session (optional): a
ClientSession
. - **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
.- session (optional): a
-
coroutine
server_info
(session=None)¶ Get information about the MongoDB server we’re connected to.
Parameters: - session (optional): a
ClientSession
.
- session (optional): a
-
coroutine
start_session
(causal_consistency=True, default_transaction_options=None)¶ Start a logical session.
This method takes the same parameters as PyMongo’s
SessionOptions
. See theclient_session
module for details.This session is created uninitialized, use it in an
await
expression to initialize it, or anasync with
statement.async def coro(): collection = client.db.collection # End the session after using it. s = await client.start_session() await s.end_session() # Or, use an "async with" statement to end the session # automatically. async 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, so we can read # the doc we just inserted, even reading from a secondary. async for doc in secondary.find(session=s): print(doc) # Run a multi-document transaction: async with await client.start_session() as s: # Note, start_transaction doesn't require "await". async with s.start_transaction(): await collection.delete_one({'x': 1}, session=s) await collection.insert_one({'x': 2}, session=s) # Exiting the "with s.start_transaction()" block while throwing an # exception automatically aborts the transaction, exiting the block # normally automatically commits it. # You can run additional transactions in the same session, so long as # you run them one at a time. async with s.start_transaction(): await collection.insert_one({'x': 3}, session=s) await collection.insert_many({'x': {'$gte': 2}}, {'$inc': {'x': 1}}, session=s)
Requires MongoDB 3.6. Do not use the same session for multiple operations concurrently. A
MotorClientSession
may only be used with the MotorClient that started it.Returns: An instance of MotorClientSession
.Changed in version 2.0: Returns a
MotorClientSession
. Before, this method returned a PyMongoClientSession
.New in version 1.2.
-
coroutine
unlock
(session=None)¶ DEPRECATED: Unlock a previously locked server.
Parameters: - session (optional): a
MotorClientSession
.
Deprecated. Users of MongoDB version 3.2 or newer can run the fsyncUnlock command directly with
command()
:await motor_client.admin.command('fsyncUnlock')
Users of MongoDB version 3.0 can query the “unlock” virtual collection:
await motor_client.admin["$cmd.sys.unlock"].find_one()
Changed in version 2.2: Deprecated.
- session (optional): a
-
watch
(pipeline=None, full_document=None, resume_after=None, max_await_time_ms=None, batch_size=None, collation=None, start_at_operation_time=None, session=None, start_after=None)¶ Watch changes on this cluster.
Returns a
MotorChangeStream
cursor which iterates over changes on all databases in this cluster. Introduced in MongoDB 4.0.See the documentation for
MotorCollection.watch()
for more details and examples.Parameters: - pipeline (optional): A list of aggregation pipeline stages to
append to an initial
$changeStream
stage. Not all pipeline stages are valid after a$changeStream
stage, see the MongoDB documentation on change streams for the supported stages. - full_document (optional): The fullDocument option to pass
to the
$changeStream
stage. Allowed values: ‘updateLookup’. When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - resume_after (optional): A resume token. If provided, the change stream will start returning changes that occur directly after the operation specified in the resume token. A resume token is the _id value of a change document.
- max_await_time_ms (optional): The maximum time in milliseconds for the server to wait for changes before responding to a getMore operation.
- batch_size (optional): The maximum number of documents to return per batch.
- collation (optional): The
Collation
to use for the aggregation. - start_at_operation_time (optional): If provided, the resulting
change stream will only return changes that occurred at or after
the specified
Timestamp
. Requires MongoDB >= 4.0. - session (optional): a
ClientSession
. - start_after (optional): The same as resume_after except that start_after can resume notifications after an invalidate event. This option and resume_after are mutually exclusive.
Returns: Changed in version 2.1: Added the
start_after
parameter.New in version 2.0.
- pipeline (optional): A list of aggregation pipeline stages to
append to an initial
-
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_reads
¶ If this instance should retry supported write operations.
-
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.