|
OpenQuizz
Une application de gestion des contenus pédagogiques
|


Public Member Functions | |
| def | __init__ (self, host=None, port=None, document_class=dict, tz_aware=None, connect=None, type_registry=None, **kwargs) |
| def | watch (self, 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) |
| def | event_listeners (self) |
| def | address (self) |
| def | primary (self) |
| def | secondaries (self) |
| def | arbiters (self) |
| def | is_primary (self) |
| def | is_mongos (self) |
| def | max_pool_size (self) |
| def | min_pool_size (self) |
| def | max_idle_time_ms (self) |
| def | nodes (self) |
| def | max_bson_size (self) |
| def | max_message_size (self) |
| def | max_write_batch_size (self) |
| def | local_threshold_ms (self) |
| def | server_selection_timeout (self) |
| def | retry_writes (self) |
| def | retry_reads (self) |
| def | close (self) |
| def | set_cursor_manager (self, manager_class) |
| def | __eq__ (self, other) |
| def | __ne__ (self, other) |
| def | __repr__ (self) |
| def | __getattr__ (self, name) |
| def | __getitem__ (self, name) |
| def | close_cursor (self, cursor_id, address=None) |
| def | kill_cursors (self, cursor_ids, address=None) |
| def | start_session (self, causal_consistency=True, default_transaction_options=None) |
| def | server_info (self, session=None) |
| def | list_databases (self, session=None, **kwargs) |
| def | list_database_names (self, session=None) |
| def | database_names (self, session=None) |
| def | drop_database (self, name_or_database, session=None) |
| def | get_default_database (self, default=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None) |
| def | get_database (self, name=None, codec_options=None, read_preference=None, write_concern=None, read_concern=None) |
| def | is_locked (self) |
| def | fsync (self, **kwargs) |
| def | unlock (self, session=None) |
| def | __enter__ (self) |
| def | __exit__ (self, exc_type, exc_val, exc_tb) |
| def | __iter__ (self) |
| def | __next__ (self) |
Public Member Functions inherited from BaseObject | |
| def | __init__ (self, codec_options, read_preference, write_concern, read_concern) |
| def | codec_options (self) |
| def | write_concern (self) |
| def | read_preference (self) |
| def | read_concern (self) |
Data Fields | |
| address | |
Static Public Attributes | |
| HOST | |
| PORT | |
| next | |
A client-side representation of a MongoDB cluster. Instances can represent either a standalone MongoDB server, a replica set, or a sharded cluster. Instances of this class are responsible for maintaining up-to-date state of the cluster, and possibly cache resources related to this, including background threads for monitoring, and connection pools.
| def __init__ | ( | self, | |
host = None, |
|||
port = None, |
|||
document_class = dict, |
|||
tz_aware = None, |
|||
connect = None, |
|||
type_registry = None, |
|||
| ** | kwargs | ||
| ) |
Client for a MongoDB instance, a replica set, or a set of mongoses.
The client object is thread-safe and has connection-pooling built in.
If an operation fails because of a network error,
:class:`~pymongo.errors.ConnectionFailure` is raised and the client
reconnects in the background. Application code should handle this
exception (recognizing that the operation failed) and then continue to
execute.
The `host` parameter can be a full `mongodb URI
<http://dochub.mongodb.org/core/connections>`_, in addition to
a simple hostname. It can also be a list of hostnames or
URIs. Any port specified in the host string(s) will override
the `port` parameter. If multiple mongodb URIs containing
database or auth information are passed, the last database,
username, and password present will be used. For username and
passwords reserved characters like ':', '/', '+' and '@' must be
percent encoded following RFC 2396::
try:
# Python 3.x
from urllib.parse import quote_plus
except ImportError:
# Python 2.x
from urllib import quote_plus
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), host)
client = MongoClient(uri)
Unix domain sockets are also supported. The socket path must be percent
encoded in the URI::
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), quote_plus(socket_path))
client = MongoClient(uri)
But not when passed as a simple hostname::
client = MongoClient('/tmp/mongodb-27017.sock')
Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The
URI must include one, and only one, hostname. The hostname will be
resolved to one or more DNS `SRV records
<https://en.wikipedia.org/wiki/SRV_record>`_ which will be used
as the seed list for connecting to the MongoDB deployment. When using
SRV URIs, the `authSource` and `replicaSet` configuration options can
be specified using `TXT records
<https://en.wikipedia.org/wiki/TXT_record>`_. See the
`Initial DNS Seedlist Discovery spec
<https://github.com/mongodb/specifications/blob/master/source/
initial-dns-seedlist-discovery/initial-dns-seedlist-discovery.rst>`_
for more details. Note that the use of SRV URIs implicitly enables
TLS support. Pass tls=false in the URI to override.
.. note:: MongoClient creation will block waiting for answers from
DNS when mongodb+srv:// URIs are used.
.. note:: Starting with version 3.0 the :class:`MongoClient`
constructor no longer blocks while connecting to the server or
servers, and it no longer raises
:class:`~pymongo.errors.ConnectionFailure` if they are
unavailable, nor :class:`~pymongo.errors.ConfigurationError`
if the user's credentials are wrong. Instead, the constructor
returns immediately and launches the connection process on
background threads. You can check if the server is available
like this::
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
.. warning:: When using PyMongo in a multiprocessing context, please
read :ref:`multiprocessing` first.
.. note:: Many of the following options can be passed using a MongoDB
URI or keyword parameters. If the same option is passed in a URI and
as a keyword parameter the keyword parameter takes precedence.
:Parameters:
- `host` (optional): hostname or IP address or Unix domain socket
path of a single mongod or mongos instance to connect to, or a
mongodb URI, or a list of hostnames / mongodb URIs. If `host` is
an IPv6 literal it must be enclosed in '[' and ']' characters
following the RFC2732 URL syntax (e.g. '[::1]' for localhost).
Multihomed and round robin DNS addresses are **not** supported.
- `port` (optional): port number on which to connect
- `document_class` (optional): default class to use for
documents returned from queries on this client
- `type_registry` (optional): instance of
:class:`~bson.codec_options.TypeRegistry` to enable encoding
and decoding of custom types.
- `tz_aware` (optional): if ``True``,
:class:`~datetime.datetime` instances returned as values
in a document by this :class:`MongoClient` will be timezone
aware (otherwise they will be naive)
- `connect` (optional): if ``True`` (the default), immediately
begin connecting to MongoDB in the background. Otherwise connect
on the first operation.
- `directConnection` (optional): if ``True``, forces this client to
connect directly to the specified MongoDB host as a standalone.
If ``false``, the client connects to the entire replica set of
which the given MongoDB host(s) is a part. If this is ``True``
and a mongodb+srv:// URI or a URI containing multiple seeds is
provided, an exception will be raised.
| **Other optional parameters can be passed as keyword arguments:**
- `maxPoolSize` (optional): 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.
- `minPoolSize` (optional): The minimum required number of concurrent
connections that the pool will maintain to each connected server.
Default is 0.
- `maxIdleTimeMS` (optional): The maximum number of milliseconds that
a connection can remain idle in the pool before being removed and
replaced. Defaults to `None` (no limit).
- `socketTimeoutMS`: (integer or None) Controls how long (in
milliseconds) the driver will wait for a response after sending an
ordinary (non-monitoring) database operation before concluding that
a network error has occurred. ``0`` or ``None`` means no timeout.
Defaults to ``None`` (no timeout).
- `connectTimeoutMS`: (integer or None) Controls how long (in
milliseconds) the driver will wait during server monitoring when
connecting a new socket to a server before concluding the server
is unavailable. ``0`` or ``None`` means no timeout.
Defaults to ``20000`` (20 seconds).
- `server_selector`: (callable or None) Optional, user-provided
function that augments server selection rules. The function should
accept as an argument a list of
:class:`~pymongo.server_description.ServerDescription` objects and
return a list of server descriptions that should be considered
suitable for the desired operation.
- `serverSelectionTimeoutMS`: (integer) Controls how long (in
milliseconds) the driver will wait to find an available,
appropriate server to carry out a database operation; while it is
waiting, multiple server monitoring operations may be carried out,
each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30
seconds).
- `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds)
a thread will wait for a socket from the pool if the pool has no
free sockets. Defaults to ``None`` (no timeout).
- `waitQueueMultiple`: (integer or None) Multiplied by maxPoolSize
to give the number of threads allowed to wait for a socket at one
time. Defaults to ``None`` (no limit).
- `heartbeatFrequencyMS`: (optional) The number of milliseconds
between periodic server checks, or None to accept the default
frequency of 10 seconds.
- `appname`: (string or None) The name of the application that
created this MongoClient instance. MongoDB 3.4 and newer will
print this value in the server log upon establishing each
connection. It is also recorded in the slow query log and
profile collections.
- `driver`: (pair or None) A driver implemented on top of PyMongo can
pass a :class:`~pymongo.driver_info.DriverInfo` to add its name,
version, and platform to the message printed in the server log when
establishing a connection.
- `event_listeners`: a list or tuple of event listeners. See
:mod:`~pymongo.monitoring` for details.
- `retryWrites`: (boolean) Whether supported write operations
executed within this MongoClient will be retried once after a
network error on MongoDB 3.6+. Defaults to ``True``.
The supported write operations are:
- :meth:`~pymongo.collection.Collection.bulk_write`, as long as
:class:`~pymongo.operations.UpdateMany` or
:class:`~pymongo.operations.DeleteMany` are not included.
- :meth:`~pymongo.collection.Collection.delete_one`
- :meth:`~pymongo.collection.Collection.insert_one`
- :meth:`~pymongo.collection.Collection.insert_many`
- :meth:`~pymongo.collection.Collection.replace_one`
- :meth:`~pymongo.collection.Collection.update_one`
- :meth:`~pymongo.collection.Collection.find_one_and_delete`
- :meth:`~pymongo.collection.Collection.find_one_and_replace`
- :meth:`~pymongo.collection.Collection.find_one_and_update`
Unsupported write operations include, but are not limited to,
:meth:`~pymongo.collection.Collection.aggregate` using the ``$out``
pipeline operator and any operation with an unacknowledged write
concern (e.g. {w: 0})). See
https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst
- `retryReads`: (boolean) Whether supported read operations
executed within this MongoClient will be retried once after a
network error on MongoDB 3.6+. Defaults to ``True``.
The supported read operations are:
:meth:`~pymongo.collection.Collection.find`,
:meth:`~pymongo.collection.Collection.find_one`,
:meth:`~pymongo.collection.Collection.aggregate` without ``$out``,
:meth:`~pymongo.collection.Collection.distinct`,
:meth:`~pymongo.collection.Collection.count`,
:meth:`~pymongo.collection.Collection.estimated_document_count`,
:meth:`~pymongo.collection.Collection.count_documents`,
:meth:`pymongo.collection.Collection.watch`,
:meth:`~pymongo.collection.Collection.list_indexes`,
:meth:`pymongo.database.Database.watch`,
:meth:`~pymongo.database.Database.list_collections`,
:meth:`pymongo.mongo_client.MongoClient.watch`,
and :meth:`~pymongo.mongo_client.MongoClient.list_databases`.
Unsupported read operations include, but are not limited to:
:meth:`~pymongo.collection.Collection.map_reduce`,
:meth:`~pymongo.collection.Collection.inline_map_reduce`,
:meth:`~pymongo.database.Database.command`,
and any getMore operation on a cursor.
Enabling retryable reads makes applications more resilient to
transient errors such as network failures, database upgrades, and
replica set failovers. For an exact definition of which errors
trigger a retry, see the `retryable reads specification
<https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.rst>`_.
- `socketKeepAlive`: (boolean) **DEPRECATED** Whether to send
periodic keep-alive packets on connected sockets. Defaults to
``True``. Disabling it is not recommended, see
https://docs.mongodb.com/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments",
- `compressors`: Comma separated list of compressors for wire
protocol compression. The list is used to negotiate a compressor
with the server. Currently supported options are "snappy", "zlib"
and "zstd". Support for snappy requires the
`python-snappy <https://pypi.org/project/python-snappy/>`_ package.
zlib support requires the Python standard library zlib module. zstd
requires the `zstandard <https://pypi.org/project/zstandard/>`_
package. By default no compression is used. Compression support
must also be enabled on the server. MongoDB 3.4+ supports snappy
compression. MongoDB 3.6 adds support for zlib. MongoDB 4.2 adds
support for zstd.
- `zlibCompressionLevel`: (int) The zlib compression level to use
when zlib is used as the wire protocol compressor. Supported values
are -1 through 9. -1 tells the zlib library to use its default
compression level (usually 6). 0 means no compression. 1 is best
speed. 9 is best compression. Defaults to -1.
- `uuidRepresentation`: The BSON representation to use when encoding
from and decoding to instances of :class:`~uuid.UUID`. Valid
values are `pythonLegacy` (the default), `javaLegacy`,
`csharpLegacy`, `standard` and `unspecified`. New applications
should consider setting this to `standard` for cross language
compatibility. See :ref:`handling-uuid-data-example` for details.
| **Write Concern options:**
| (Only set if passed. No default values.)
- `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). Passing w=0 **disables write
acknowledgement** and all other write concern options.
- `wTimeoutMS`: (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. Passing wTimeoutMS=0
will cause **write operations to wait indefinitely**.
- `journal`: 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`.
| **Replica set keyword arguments for connecting with a replica set
- either directly or via a mongos:**
- `replicaSet`: (string or None) The name of the replica set to
connect to. The driver will verify that all servers it connects to
match this name. Implies that the hosts specified are a seed list
and the driver should attempt to find all members of the set.
Defaults to ``None``.
| **Read Preference:**
- `readPreference`: The replica set read preference for this client.
One of ``primary``, ``primaryPreferred``, ``secondary``,
``secondaryPreferred``, or ``nearest``. Defaults to ``primary``.
- `readPreferenceTags`: Specifies a tag set as a comma-separated list
of colon-separated key-value pairs. For example ``dc:ny,rack:1``.
Defaults to ``None``.
- `maxStalenessSeconds`: (integer) The maximum estimated
length of time a replica set secondary can fall behind the primary
in replication before it will no longer be selected for operations.
Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds
is set, it must be a positive integer greater than or equal to
90 seconds.
.. seealso:: :doc:`/examples/server_selection`
| **Authentication:**
- `username`: A string.
- `password`: A string.
Although username and password must be percent-escaped in a MongoDB
URI, they must not be percent-escaped when passed as parameters. In
this example, both the space and slash special characters are passed
as-is::
MongoClient(username="user name", password="pass/word")
- `authSource`: The database to authenticate on. Defaults to the
database specified in the URI, if provided, or to "admin".
- `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options.
If no mechanism is specified, PyMongo automatically uses MONGODB-CR
when connected to a pre-3.0 version of MongoDB, SCRAM-SHA-1 when
connected to MongoDB 3.0 through 3.6, and negotiates the mechanism
to use (SCRAM-SHA-1 or SCRAM-SHA-256) when connected to MongoDB
4.0+.
- `authMechanismProperties`: Used to specify authentication mechanism
specific options. To specify the service name for GSSAPI
authentication pass authMechanismProperties='SERVICE_NAME:<service
name>'.
To specify the session token for MONGODB-AWS authentication pass
``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.
.. seealso:: :doc:`/examples/authentication`
| **TLS/SSL configuration:**
- `tls`: (boolean) If ``True``, create the connection to the server
using transport layer security. Defaults to ``False``.
- `tlsInsecure`: (boolean) Specify whether TLS constraints should be
relaxed as much as possible. Setting ``tlsInsecure=True`` implies
``tlsAllowInvalidCertificates=True`` and
``tlsAllowInvalidHostnames=True``. Defaults to ``False``. Think
very carefully before setting this to ``True`` as it dramatically
reduces the security of TLS.
- `tlsAllowInvalidCertificates`: (boolean) If ``True``, continues
the TLS handshake regardless of the outcome of the certificate
verification process. If this is ``False``, and a value is not
provided for ``tlsCAFile``, PyMongo will attempt to load system
provided CA certificates. If the python version in use does not
support loading system CA certificates then the ``tlsCAFile``
parameter must point to a file of CA certificates.
``tlsAllowInvalidCertificates=False`` implies ``tls=True``.
Defaults to ``False``. Think very carefully before setting this
to ``True`` as that could make your application vulnerable to
man-in-the-middle attacks.
- `tlsAllowInvalidHostnames`: (boolean) If ``True``, disables TLS
hostname verification. ``tlsAllowInvalidHostnames=False`` implies
``tls=True``. Defaults to ``False``. Think very carefully before
setting this to ``True`` as that could make your application
vulnerable to man-in-the-middle attacks.
- `tlsCAFile`: A file containing a single or a bundle of
"certification authority" certificates, which are used to validate
certificates passed from the other end of the connection.
Implies ``tls=True``. Defaults to ``None``.
- `tlsCertificateKeyFile`: A file containing the client certificate
and private key. If you want to pass the certificate and private
key as separate files, use the ``ssl_certfile`` and ``ssl_keyfile``
options instead. Implies ``tls=True``. Defaults to ``None``.
- `tlsCRLFile`: A file containing a PEM or DER formatted
certificate revocation list. Only supported by python 2.7.9+
(pypy 2.5.1+). Implies ``tls=True``. Defaults to ``None``.
- `tlsCertificateKeyFilePassword`: The password or passphrase for
decrypting the private key in ``tlsCertificateKeyFile`` or
``ssl_keyfile``. Only necessary if the private key is encrypted.
Only supported by python 2.7.9+ (pypy 2.5.1+) and 3.3+. Defaults
to ``None``.
- `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
certificate revocation status checking via the OCSP responder
specified on the server certificate. Defaults to ``False``.
- `ssl`: (boolean) Alias for ``tls``.
- `ssl_certfile`: The certificate file used to identify the local
connection against mongod. Implies ``tls=True``. Defaults to
``None``.
- `ssl_keyfile`: The private keyfile used to identify the local
connection against mongod. Can be omitted if the keyfile is
included with the ``tlsCertificateKeyFile``. Implies ``tls=True``.
Defaults to ``None``.
| **Read Concern options:**
| (If not set explicitly, this will use the server default)
- `readConcernLevel`: (string) The read concern level specifies the
level of isolation for read operations. For example, a read
operation using a read concern level of ``majority`` will only
return data that has been written to a majority of nodes. If the
level is left unspecified, the server default will be used.
| **Client side encryption options:**
| (If not set explicitly, client side encryption will not be enabled.)
- `auto_encryption_opts`: A
:class:`~pymongo.encryption_options.AutoEncryptionOpts` which
configures this client to automatically encrypt collection commands
and automatically decrypt results. See
:ref:`automatic-client-side-encryption` for an example.
.. mongodoc:: connections
.. versionchanged:: 3.11
Added the following keyword arguments and URI options:
- ``tlsDisableOCSPEndpointCheck``
- ``directConnection``
.. versionchanged:: 3.9
Added the ``retryReads`` keyword argument and URI option.
Added the ``tlsInsecure`` keyword argument and URI option.
The following keyword arguments and URI options were deprecated:
- ``wTimeout`` was deprecated in favor of ``wTimeoutMS``.
- ``j`` was deprecated in favor of ``journal``.
- ``ssl_cert_reqs`` was deprecated in favor of
``tlsAllowInvalidCertificates``.
- ``ssl_match_hostname`` was deprecated in favor of
``tlsAllowInvalidHostnames``.
- ``ssl_ca_certs`` was deprecated in favor of ``tlsCAFile``.
- ``ssl_certfile`` was deprecated in favor of
``tlsCertificateKeyFile``.
- ``ssl_crlfile`` was deprecated in favor of ``tlsCRLFile``.
- ``ssl_pem_passphrase`` was deprecated in favor of
``tlsCertificateKeyFilePassword``.
.. versionchanged:: 3.9
``retryWrites`` now defaults to ``True``.
.. versionchanged:: 3.8
Added the ``server_selector`` keyword argument.
Added the ``type_registry`` keyword argument.
.. versionchanged:: 3.7
Added the ``driver`` keyword argument.
.. versionchanged:: 3.6
Added support for mongodb+srv:// URIs.
Added the ``retryWrites`` keyword argument and URI option.
.. versionchanged:: 3.5
Add ``username`` and ``password`` options. Document the
``authSource``, ``authMechanism``, and ``authMechanismProperties``
options.
Deprecated the ``socketKeepAlive`` keyword argument and URI option.
``socketKeepAlive`` now defaults to ``True``.
.. versionchanged:: 3.0
:class:`~pymongo.mongo_client.MongoClient` is now the one and only
client class for a standalone server, mongos, or replica set.
It includes the functionality that had been split into
:class:`~pymongo.mongo_client.MongoReplicaSetClient`: it can connect
to a replica set, discover all its members, and monitor the set for
stepdowns, elections, and reconfigs.
The :class:`~pymongo.mongo_client.MongoClient` constructor no
longer blocks while connecting to the server or servers, and it no
longer raises :class:`~pymongo.errors.ConnectionFailure` if they
are unavailable, nor :class:`~pymongo.errors.ConfigurationError`
if the user's credentials are wrong. Instead, the constructor
returns immediately and launches the connection process on
background threads.
Therefore the ``alive`` method is removed since it no longer
provides meaningful information; even if the client is disconnected,
it may discover a server in time to fulfill the next operation.
In PyMongo 2.x, :class:`~pymongo.MongoClient` accepted a list of
standalone MongoDB servers and used the first it could connect to::
MongoClient(['host1.com:27017', 'host2.com:27017'])
A list of multiple standalones is no longer supported; if multiple
servers are listed they must be members of the same replica set, or
mongoses in the same sharded cluster.
The behavior for a list of mongoses is changed from "high
availability" to "load balancing". Before, the client connected to
the lowest-latency mongos in the list, and used it until a network
error prompted it to re-evaluate all mongoses' latencies and
reconnect to one of them. In PyMongo 3, the client monitors its
network latency to all the mongoses continuously, and distributes
operations evenly among those with the lowest latency. See
:ref:`mongos-load-balancing` for more information.
The ``connect`` option is added.
The ``start_request``, ``in_request``, and ``end_request`` methods
are removed, as well as the ``auto_start_request`` option.
The ``copy_database`` method is removed, see the
:doc:`copy_database examples </examples/copydb>` for alternatives.
The :meth:`MongoClient.disconnect` method is removed; it was a
synonym for :meth:`~pymongo.MongoClient.close`.
:class:`~pymongo.mongo_client.MongoClient` no longer returns an
instance of :class:`~pymongo.database.Database` for attribute names
with leading underscores. You must use dict-style lookups instead::
client['__my_database__']
Not::
client.__my_database__
| def __enter__ | ( | self | ) |
| def __eq__ | ( | self, | |
| other | |||
| ) |
| def __exit__ | ( | self, | |
| exc_type, | |||
| exc_val, | |||
| exc_tb | |||
| ) |
| def __getattr__ | ( | self, | |
| name | |||
| ) |
Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get
| def __getitem__ | ( | self, | |
| name | |||
| ) |
Get a database by name. Raises :class:`~pymongo.errors.InvalidName` if an invalid database name is used. :Parameters: - `name`: the name of the database to get
| def __iter__ | ( | self | ) |
| def __ne__ | ( | self, | |
| other | |||
| ) |
| def __next__ | ( | self | ) |
| def __repr__ | ( | self | ) |
Reimplemented in MongoReplicaSetClient.
| def address | ( | self | ) |
(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if the client is load-balancing among mongoses, since there is no single address. Use :attr:`nodes` instead. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. .. versionadded:: 3.0
| def arbiters | ( | self | ) |
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.
| def close | ( | self | ) |
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 :exc:`~.errors.InvalidOperation`. .. versionchanged:: 3.6 End all server sessions created by this client.
| def close_cursor | ( | self, | |
| cursor_id, | |||
address = None |
|||
| ) |
DEPRECATED - Send a kill cursors message soon with the given id.
Raises :class:`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 :class:`~pymongo.cursor.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.
.. versionchanged:: 3.7
Deprecated.
.. versionchanged:: 3.0
Added ``address`` parameter.
| def database_names | ( | self, | |
session = None |
|||
| ) |
**DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :meth:`list_database_names` instead.
.. versionchanged:: 3.6
Added ``session`` parameter.
| def drop_database | ( | self, | |
| name_or_database, | |||
session = None |
|||
| ) |
Drop a database.
Raises :class:`TypeError` if `name_or_database` is not an instance of
:class:`basestring` (:class:`str` in python 3) or
:class:`~pymongo.database.Database`.
:Parameters:
- `name_or_database`: the name of a database to drop, or a
:class:`~pymongo.database.Database` instance representing the
database to drop
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
.. note:: The :attr:`~pymongo.mongo_client.MongoClient.write_concern` of
this client is automatically applied to this operation when using
MongoDB >= 3.4.
.. versionchanged:: 3.4
Apply this client's write concern automatically to this operation
when connected to MongoDB >= 3.4.
| def event_listeners | ( | self | ) |
The event listeners registered for this client. See :mod:`~pymongo.monitoring` for details.
| def fsync | ( | self, | |
| ** | 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
:class:`~pymongo.client_session.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)
Deprecated. Run the `fsync command`_ directly with
:meth:`~pymongo.database.Database.command` instead. For example::
client.admin.command('fsync', lock=True)
.. versionchanged:: 3.11
Deprecated.
.. versionchanged:: 3.6
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.
.. _fsync command: https://docs.mongodb.com/manual/reference/command/fsync/
| def get_database | ( | self, | |
name = None, |
|||
codec_options = None, |
|||
read_preference = None, |
|||
write_concern = None, |
|||
read_concern = None |
|||
| ) |
Get a :class:`~pymongo.database.Database` with the given name and
options.
Useful for creating a :class:`~pymongo.database.Database` with
different codec options, read preference, and/or write concern from
this :class:`MongoClient`.
>>> client.read_preference
Primary()
>>> db1 = client.test
>>> db1.read_preference
Primary()
>>> from pymongo import ReadPreference
>>> db2 = client.get_database(
... 'test', read_preference=ReadPreference.SECONDARY)
>>> db2.read_preference
Secondary(tag_sets=None)
:Parameters:
- `name` (optional): The name of the database - a string. If ``None``
(the default) the database named in the MongoDB connection URI is
returned.
- `codec_options` (optional): An instance of
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) the :attr:`codec_options` of this :class:`MongoClient` is
used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) the :attr:`read_preference` of this
:class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
for options.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) the :attr:`write_concern` of this :class:`MongoClient` is
used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) the :attr:`read_concern` of this :class:`MongoClient` is
used.
.. versionchanged:: 3.5
The `name` parameter is now optional, defaulting to the database
named in the MongoDB connection URI.
| def get_default_database | ( | self, | |
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
:class:`~bson.codec_options.CodecOptions`. If ``None`` (the
default) the :attr:`codec_options` of this :class:`MongoClient` is
used.
- `read_preference` (optional): The read preference to use. If
``None`` (the default) the :attr:`read_preference` of this
:class:`MongoClient` is used. See :mod:`~pymongo.read_preferences`
for options.
- `write_concern` (optional): An instance of
:class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
default) the :attr:`write_concern` of this :class:`MongoClient` is
used.
- `read_concern` (optional): An instance of
:class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
default) the :attr:`read_concern` of this :class:`MongoClient` is
used.
.. versionchanged:: 3.8
Undeprecated. Added the ``default``, ``codec_options``,
``read_preference``, ``write_concern`` and ``read_concern``
parameters.
.. versionchanged:: 3.5
Deprecated, use :meth:`get_database` instead.
| def is_locked | ( | self | ) |
**DEPRECATED**: Is this server locked? While locked, all write
operations are blocked, although read operations may still be allowed.
Use :meth:`unlock` to unlock.
Deprecated. Users of MongoDB version 3.2 or newer can run the
`currentOp command`_ directly with
:meth:`~pymongo.database.Database.command`::
is_locked = client.admin.command('currentOp').get('fsyncLock')
Users of MongoDB version 2.6 and 3.0 can query the "inprog" virtual
collection::
is_locked = client.admin["$cmd.sys.inprog"].find_one().get('fsyncLock')
.. versionchanged:: 3.11
Deprecated.
.. _currentOp command: https://docs.mongodb.com/manual/reference/command/currentOp/
| def is_mongos | ( | self | ) |
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..
| def is_primary | ( | self | ) |
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.
| def kill_cursors | ( | self, | |
| cursor_ids, | |||
address = None |
|||
| ) |
DEPRECATED - Send a kill cursors message soon with the given ids.
Raises :class:`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.
.. versionchanged:: 3.3
Deprecated.
.. versionchanged:: 3.0
Now accepts an `address` argument. Schedules the cursors to be
closed on a background thread instead of sending the message
immediately.
| def list_database_names | ( | self, | |
session = None |
|||
| ) |
Get a list of the names of all databases on the connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionadded:: 3.6
| def list_databases | ( | self, | |
session = None, |
|||
| ** | kwargs | ||
| ) |
Get a cursor over the databases of the connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `**kwargs` (optional): Optional parameters of the
`listDatabases command
<https://docs.mongodb.com/manual/reference/command/listDatabases/>`_
can be passed as keyword arguments to this method. The supported
options differ by server version.
:Returns:
An instance of :class:`~pymongo.command_cursor.CommandCursor`.
.. versionadded:: 3.6
| def local_threshold_ms | ( | self | ) |
The local threshold for this instance.
| def max_bson_size | ( | self | ) |
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.
| def max_idle_time_ms | ( | self | ) |
The maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit).
| def max_message_size | ( | self | ) |
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.
| def max_pool_size | ( | self | ) |
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 :exc:`~pymongo.errors.ConnectionFailure` after a timeout. By default ``waitQueueTimeoutMS`` is not set.
| def max_write_batch_size | ( | self | ) |
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.
| def min_pool_size | ( | self | ) |
The minimum required number of concurrent connections that the pool will maintain to each connected server. Default is 0.
| def nodes | ( | self | ) |
Set of all currently connected servers. .. warning:: When connected to a replica set the value of :attr:`nodes` can change over time as :class:`MongoClient`'s view of the replica set changes. :attr:`nodes` can also be an empty set when :class:`MongoClient` is first instantiated and hasn't yet connected to any servers, or a network partition causes it to lose connection to all servers.
| def primary | ( | self | ) |
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. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in.
| def retry_reads | ( | self | ) |
If this instance should retry supported write operations.
| def retry_writes | ( | self | ) |
If this instance should retry supported write operations.
| def secondaries | ( | self | ) |
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. .. versionadded:: 3.0 MongoClient gained this property in version 3.0 when MongoReplicaSetClient's functionality was merged in.
| def server_info | ( | self, | |
session = None |
|||
| ) |
Get information about the MongoDB server we're connected to.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
| def server_selection_timeout | ( | self | ) |
The server selection timeout for this instance in seconds.
| def set_cursor_manager | ( | self, | |
| manager_class | |||
| ) |
DEPRECATED - Set this client's cursor manager. Raises :class:`TypeError` if `manager_class` is not a subclass of :class:`~pymongo.cursor_manager.CursorManager`. A cursor manager handles closing cursors. Different managers can implement different policies in terms of when to actually kill a cursor that has been closed. :Parameters: - `manager_class`: cursor manager to use .. versionchanged:: 3.3 Deprecated, for real this time. .. versionchanged:: 3.0 Undeprecated.
| def start_session | ( | self, | |
causal_consistency = True, |
|||
default_transaction_options = None |
|||
| ) |
Start a logical session. This method takes the same parameters as :class:`~pymongo.client_session.SessionOptions`. See the :mod:`~pymongo.client_session` module for details and examples. Requires MongoDB 3.6. It is an error to call :meth:`start_session` if this client has been authenticated to multiple databases using the deprecated method :meth:`~pymongo.database.Database.authenticate`. A :class:`~pymongo.client_session.ClientSession` may only be used with the MongoClient that started it. :class:`ClientSession` instances are **not thread-safe or fork-safe**. They can only be used by one thread or process at a time. A single :class:`ClientSession` cannot be used to run multiple operations concurrently. :Returns: An instance of :class:`~pymongo.client_session.ClientSession`. .. versionadded:: 3.6
| def unlock | ( | self, | |
session = None |
|||
| ) |
**DEPRECATED**: Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
Deprecated. Users of MongoDB version 3.2 or newer can run the
`fsyncUnlock command`_ directly with
:meth:`~pymongo.database.Database.command`::
client.admin.command('fsyncUnlock')
Users of MongoDB version 2.6 and 3.0 can query the "unlock" virtual
collection::
client.admin["$cmd.sys.unlock"].find_one()
.. versionchanged:: 3.11
Deprecated.
.. versionchanged:: 3.6
Added ``session`` parameter.
.. _fsyncUnlock command: https://docs.mongodb.com/manual/reference/command/fsyncUnlock/
| def watch | ( | self, | |
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.
Performs an aggregation with an implicit initial ``$changeStream``
stage and returns a
:class:`~pymongo.change_stream.ClusterChangeStream` cursor which
iterates over changes on all databases on this cluster.
Introduced in MongoDB 4.0.
.. code-block:: python
with client.watch() as stream:
for change in stream:
print(change)
The :class:`~pymongo.change_stream.ClusterChangeStream` iterable
blocks until the next change document is returned or an error is
raised. If the
:meth:`~pymongo.change_stream.ClusterChangeStream.next` method
encounters a network error when retrieving a batch from the server,
it will automatically attempt to recreate the cursor such that no
change events are missed. Any error encountered during the resume
attempt indicates there may be an outage and will be raised.
.. code-block:: python
try:
with client.watch(
[{'$match': {'operationType': 'insert'}}]) as stream:
for insert_change in stream:
print(insert_change)
except pymongo.errors.PyMongoError:
# The ChangeStream encountered an unrecoverable error or the
# resume attempt failed to recreate the cursor.
logging.error('...')
For a precise description of the resume process see the
`change streams specification`_.
: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 to pass as an option
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 :class:`~pymongo.collation.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 :class:`~bson.timestamp.Timestamp`. Requires
MongoDB >= 4.0.
- `session` (optional): a
:class:`~pymongo.client_session.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:
A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.
.. versionchanged:: 3.9
Added the ``start_after`` parameter.
.. versionadded:: 3.7
.. mongodoc:: changeStreams
.. _change streams specification:
https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
| address |
|
static |
|
static |
|
static |