pymongo API Reference
Full documentation for pymongo (4.17.0)
pymongo.ASCENDING
Python Library Documentation: int object
class int(object)
| 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
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is equal to the original int.
|
| The ratio is in lowest terms and has a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| is_integer(self, /)
| Returns True. Exists for duck type compatibility with float.is_integer.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes. Default
| is length 1.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False)
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
pymongo.AsyncMongoClient
Python Library Documentation: class AsyncMongoClient in module pymongo.asynchronous.mongo_client
class AsyncMongoClient(pymongo.common.BaseObject, typing.Generic)
| AsyncMongoClient(host: 'Optional[Union[str, Sequence[str]]]' = None, port: 'Optional[int]' = None, document_class: 'Optional[Type[_DocumentType]]' = None, tz_aware: 'Optional[bool]' = None, connect: 'Optional[bool]' = None, type_registry: 'Optional[TypeRegistry]' = None, **kwargs: 'Any') -> 'None'
|
| Method resolution order:
| AsyncMongoClient
| pymongo.common.BaseObject
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| async __aenter__(self) -> 'AsyncMongoClient[_DocumentType]'
|
| async __aexit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __del__(self) -> 'None'
| Check that this AsyncMongoClient has been closed and issue a warning if not.
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, name: 'str') -> 'database.AsyncDatabase[_DocumentType]'
| Get a database by name.
|
| Raises :class:`~pymongo.errors.InvalidName` if an invalid
| database name is used.
|
| :param name: the name of the database to get
|
| __getitem__(self, name: 'str') -> 'database.AsyncDatabase[_DocumentType]'
| Get a database by name.
|
| Raises :class:`~pymongo.errors.InvalidName` if an invalid
| database name is used.
|
| :param name: the name of the database to get
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, host: 'Optional[Union[str, Sequence[str]]]' = None, port: 'Optional[int]' = None, document_class: 'Optional[Type[_DocumentType]]' = None, tz_aware: 'Optional[bool]' = None, connect: 'Optional[bool]' = None, type_registry: 'Optional[TypeRegistry]' = None, **kwargs: 'Any') -> 'None'
| Client for a MongoDB instance, a replica set, or a set of mongoses.
|
| .. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of
| False instead of None.
| For more details, see the relevant section of the PyMongo 4.x migration guide:
| :ref:`pymongo4-migration-direct-connection`.
|
| 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.
|
| Best practice is to call :meth:`AsyncMongoClient.close` when the client is no longer needed,
| or use the client in a with statement::
|
| async with AsyncMongoClient(url) as client:
| # Use client here.
|
| The `host` parameter can be a full `mongodb URI
| <https://dochub.mongodb.org/core/connections>`_, in addition to
| a simple hostname. It can also be a list of hostnames but no more
| than one URI. Any port specified in the host string(s) will override
| the `port` parameter. For username and
| passwords reserved characters like ':', '/', '+' and '@' must be
| percent encoded following RFC 2396::
|
| from urllib.parse import quote_plus
|
| uri = "mongodb://%s:%s@%s" % (
| quote_plus(user), quote_plus(password), host)
| client = AsyncMongoClient(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 = AsyncMongoClient(uri)
|
| But not when passed as a simple hostname::
|
| client = AsyncMongoClient('/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.md>`_
| for more details. Note that the use of SRV URIs implicitly enables
| TLS support. Pass tls=false in the URI to override.
|
| .. note:: AsyncMongoClient creation will block waiting for answers from
| DNS when mongodb+srv:// URIs are used.
|
| .. note:: Starting with version 3.0 the :class:`AsyncMongoClient`
| 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 = AsyncMongoClient()
| try:
| # The ping command is cheap and does not require auth.
| client.admin.command('ping')
| except ConnectionFailure:
| print("Server not available")
|
| .. warning:: When using PyMongo in a multiprocessing context, please
| read `PyMongo multiprocessing <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/mongoclient/#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.
|
| :param host: 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 (but no more than one mongodb
| URI). 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.
| :param port: port number on which to connect
| :param document_class: default class to use for
| documents returned from queries on this client
| :param tz_aware: if ``True``,
| :class:`~datetime.datetime` instances returned as values
| in a document by this :class:`AsyncMongoClient` will be timezone
| aware (otherwise they will be naive)
| :param connect: **Not supported by AsyncMongoClient**.
| :param type_registry: instance of
| :class:`~bson.codec_options.TypeRegistry` to enable encoding
| and decoding of custom types.
| :param kwargs: **Additional optional parameters available as keyword arguments:**
|
| - `datetime_conversion` (optional): Specifies how UTC datetimes should be decoded
| within BSON. Valid options include 'datetime_ms' to return as a
| DatetimeMS, 'datetime' to return as a datetime.datetime and
| raising a ValueError for out-of-range values, 'datetime_auto' to
| return DatetimeMS objects when the underlying datetime is
| out-of-range and 'datetime_clamp' to clamp to the minimum and
| maximum possible datetimes. Defaults to 'datetime'. See
| `handling out of range datetimes <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times/#handling-out-of-range-datetimes>`_ for details.
| - `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.
| - `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. Can be
| either 0 or None, in which case there is no limit on the number
| of concurrent connections.
| - `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).
| - `maxConnecting` (optional): The maximum number of connections that
| each pool can establish concurrently. Defaults to `2`.
| - `timeoutMS`: (integer or None) Controls how long (in
| milliseconds) the driver will wait when executing an operation
| (including retry attempts) before raising a timeout error.
| ``0`` or ``None`` means no timeout.
| - `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).
| - `heartbeatFrequencyMS`: (optional) The number of milliseconds
| between periodic server checks, or None to accept the default
| frequency of 10 seconds.
| - `serverMonitoringMode`: (optional) The server monitoring mode to use.
| Valid values are the strings: "auto", "stream", "poll". Defaults to "auto".
| - `appname`: (string or None) The name of the application that
| created this AsyncMongoClient instance. The server will log this value
| 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 AsyncMongoClient will be retried once after a
| network error. Defaults to ``True``.
| The supported write operations are:
|
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, as long as
| :class:`~pymongo.asynchronous.operations.UpdateMany` or
| :class:`~pymongo.asynchronous.operations.DeleteMany` are not included.
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.delete_one`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_one`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_many`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.replace_one`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.update_one`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_delete`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_replace`
| - :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_update`
|
| Unsupported write operations include, but are not limited to,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.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.md
| - `retryReads`: (boolean) Whether supported read operations
| executed within this AsyncMongoClient will be retried once after a
| network error. Defaults to ``True``.
| The supported read operations are:
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.find`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` without ``$out``,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.distinct`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.count`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.estimated_document_count`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.count_documents`,
| :meth:`pymongo.asynchronous.collection.AsyncCollection.watch`,
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.list_indexes`,
| :meth:`pymongo.asynchronous.database.AsyncDatabase.watch`,
| :meth:`~pymongo.asynchronous.database.AsyncDatabase.list_collections`,
| :meth:`pymongo.asynchronous.mongo_client.AsyncMongoClient.watch`,
| and :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.list_databases`.
|
| Unsupported read operations include, but are not limited to
| :meth:`~pymongo.asynchronous.database.AsyncDatabase.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.md>`_.
|
| - `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. For
| Python before 3.14 zstd requires the `backports.zstd <https://pypi.org/project/backports.zstd/>`_
| package. By default no compression is used. Compression support
| must also be enabled on the server. MongoDB 3.6+ supports snappy
| and zlib compression. MongoDB 4.2+ adds support for zstd.
| See `compress network traffic <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/network-compression/#compress-network-traffic>`_ for details.
| - `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 the strings: "standard", "pythonLegacy", "javaLegacy",
| "csharpLegacy", and "unspecified" (the default). New applications
| should consider setting this to "standard" for cross language
| compatibility. See `handling UUID data <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/uuid/#unspecified>`_ for details.
| - `unicode_decode_error_handler`: The error handler to apply when
| a Unicode-related error occurs during BSON decoding that would
| otherwise raise :exc:`UnicodeDecodeError`. Valid options include
| 'strict', 'replace', 'backslashreplace', 'surrogateescape', and
| 'ignore'. Defaults to 'strict'.
| - `srvServiceName`: (string) The SRV service name to use for
| "mongodb+srv://" URIs. Defaults to "mongodb". Use it like so::
|
| AsyncMongoClient("mongodb+srv://example.com/?srvServiceName=customname")
| - `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will
| connect to. More specifically, when a "mongodb+srv://" connection string
| resolves to more than srvMaxHosts number of hosts, the client will randomly
| choose an srvMaxHosts sized subset of hosts.
|
|
| | **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`: **DEPRECATED** (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`. 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:: `Customize Server Selection <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/server-selection/#customize-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::
|
| AsyncMongoClient(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 negotiates the
| mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server.
| - `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:: `Authentication <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security/authentication/#authentication-mechanisms>`_
|
| | **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
| on-path attackers.
| - `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 on-path attackers.
| - `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. Implies ``tls=True``. Defaults to ``None``.
| - `tlsCRLFile`: A file containing a PEM or DER formatted
| certificate revocation list. Implies ``tls=True``. Defaults to
| ``None``.
| - `tlsCertificateKeyFilePassword`: The password or passphrase for
| decrypting the private key in ``tlsCertificateKeyFile``. Only
| necessary if the private key is encrypted. Defaults to ``None``.
| - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
| certificate revocation status checking via the OCSP responder
| specified on the server certificate.
| ``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``.
| Defaults to ``False``.
| - `ssl`: (boolean) Alias for ``tls``.
|
| | **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
| `client-side field level encryption <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security/in-use-encryption/#client-side-field-level-encryption>`_ for an example.
| If a :class:`AsyncMongoClient` is configured with
| ``auto_encryption_opts`` and a non-None ``maxPoolSize``, a
| separate internal ``AsyncMongoClient`` is created if any of the
| following are true:
|
| - A ``key_vault_client`` is not passed to
| :class:`~pymongo.encryption_options.AutoEncryptionOpts`
| - ``bypass_auto_encrpytion=False`` is passed to
| :class:`~pymongo.encryption_options.AutoEncryptionOpts`
|
| | **Stable API options:**
| | (If not set explicitly, Stable API will not be enabled.)
|
| - `server_api`: A
| :class:`~pymongo.server_api.ServerApi` which configures this
| client to use Stable API. See `versioned API <https://www.mongodb.com/docs/manual/reference/stable-api/#what-is-the-stable-api--and-should-you-use-it->`_ for
| details.
|
| | **Overload retry options:**
|
| - `max_adaptive_retries`: (int) How many retries to allow for overload errors. Defaults to ``2``.
| - `enable_overload_retargeting`: (boolean) Whether overload retargeting is enabled for this client.
| If enabled, server overload errors will cause retry attempts to select a server that has not yet returned an overload error, if possible.
| Defaults to ``False``.
|
| .. seealso:: The MongoDB documentation on `connections <https://dochub.mongodb.org/core/connections>`_.
|
| .. versionchanged:: 4.17
| Added the ``max_adaptive_retries`` and ``enable_overload_retargeting`` URI and keyword arguments.
|
| .. versionchanged:: 4.5
| Added the ``serverMonitoringMode`` keyword argument.
|
| .. versionchanged:: 4.2
| Added the ``timeoutMS`` keyword argument.
|
| .. versionchanged:: 4.0
|
| - Removed the fsync, unlock, is_locked, database_names, and
| close_cursor methods.
| See the :ref:`pymongo4-migration-guide`.
| - Removed the ``waitQueueMultiple`` and ``socketKeepAlive``
| keyword arguments.
| - The default for `uuidRepresentation` was changed from
| ``pythonLegacy`` to ``unspecified``.
| - Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and
| keyword arguments.
|
| .. versionchanged:: 3.12
| Added the ``server_api`` keyword argument.
| The following keyword arguments were deprecated:
|
| - ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor
| of ``tlsCertificateKeyFile``.
|
| .. 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.asynchronous.mongo_client.AsyncMongoClient` 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.asynchronous.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.asynchronous.mongo_client.AsyncMongoClient` 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.asynchronous.AsyncMongoClient` accepted a list of
| standalone MongoDB servers and used the first it could connect to::
|
| AsyncMongoClient(['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
| `load balancing <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-targets/#replica-sets>`_ 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
| `Copy and Clone Databases <https://www.mongodb.com/docs/database-tools/mongodump/mongodump-examples/#copy-and-clone-databases>`_ for alternatives.
|
| The :meth:`AsyncMongoClient.disconnect` method is removed; it was a
| synonym for :meth:`~pymongo.asynchronous.AsyncMongoClient.close`.
|
| :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` no longer returns an
| instance of :class:`~pymongo.asynchronous.database.AsyncDatabase` for attribute names
| with leading underscores. You must use dict-style lookups instead::
|
| client['__my_database__']
|
| Not::
|
| client.__my_database__
|
| .. versionchanged:: 4.7
| Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`.
|
| .. versionchanged:: 4.9
| The default value of ``connect`` is changed to ``False`` when running in a
| Function-as-a-service environment.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __next__(self) -> 'NoReturn'
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| async aclose = close(self) -> 'None'
|
| async aconnect(self) -> 'None'
| Explicitly connect to MongoDB asynchronously instead of on the first operation.
|
| append_metadata(self, driver_info: 'DriverInfo') -> 'None'
| Appends the given metadata to existing driver metadata.
|
| :param driver_info: a :class:`~pymongo.driver_info.DriverInfo`
|
| .. versionadded:: 4.14
|
| async bulk_write(self, models: 'Sequence[_WriteOp]', session: 'Optional[AsyncClientSession]' = None, ordered: 'bool' = True, verbose_results: 'bool' = False, bypass_document_validation: 'Optional[bool]' = None, comment: 'Optional[Any]' = None, let: 'Optional[Mapping[str, Any]]' = None, write_concern: 'Optional[WriteConcern]' = None) -> 'ClientBulkWriteResult'
| Send a batch of write operations, potentially across multiple namespaces, to the server.
|
| Requests are passed as a list of write operation instances (
| :class:`~pymongo.operations.InsertOne`,
| :class:`~pymongo.operations.UpdateOne`,
| :class:`~pymongo.operations.UpdateMany`,
| :class:`~pymongo.operations.ReplaceOne`,
| :class:`~pymongo.operations.DeleteOne`, or
| :class:`~pymongo.operations.DeleteMany`).
|
| >>> async for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| ...
| >>> async for doc in db.coll.find({}):
| ... print(doc)
| ...
| {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
| ...
| >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
| >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
| >>> models = [InsertOne(namespace="db.test", document={'y': 1}),
| ... DeleteOne(namespace="db.test", filter={'x': 1}),
| ... InsertOne(namespace="db.coll", document={'y': 2}),
| ... ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)]
| >>> result = await client.bulk_write(models=models)
| >>> result.inserted_count
| 2
| >>> result.deleted_count
| 1
| >>> result.modified_count
| 0
| >>> result.upserted_count
| 1
| >>> async for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
| {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
| ...
| >>> async for doc in db.coll.find({}):
| ... print(doc)
| ...
| {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
| {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')}
|
| :param models: A list of write operation instances.
| :param session: (optional) An instance of
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
| :param ordered: If ``True`` (the default), requests will be
| performed on the server serially, in the order provided. If an error
| occurs all remaining operations are aborted. If ``False``, requests
| will be still performed on the server serially, in the order provided,
| but all operations will be attempted even if any errors occur.
| :param verbose_results: If ``True``, detailed results for each
| successful operation will be included in the returned
| :class:`~pymongo.results.ClientBulkWriteResult`. Default is ``False``.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is ``False``.
| :param comment: (optional) A user-provided comment to attach to this
| command.
| :param let: (optional) Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param write_concern: (optional) The write concern to use for this bulk write.
|
| :return: An instance of :class:`~pymongo.results.ClientBulkWriteResult`.
|
| .. seealso:: For more info, see `Client Bulk Write <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write/#client-bulk-write-example>`_.
|
| .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_
|
| .. note:: requires MongoDB server version 8.0+.
|
| .. versionadded:: 4.9
|
| async close(self) -> 'None'
| Cleanup client resources and disconnect from MongoDB.
|
| 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.
|
| .. versionchanged:: 4.0
| Once closed, the client cannot be used again and any attempt will
| raise :exc:`~pymongo.errors.InvalidOperation`.
|
| .. versionchanged:: 3.6
| End all server sessions created by this client.
|
| async drop_database(self, name_or_database: 'Union[str, database.AsyncDatabase[_DocumentTypeArg]]', session: 'Optional[client_session.AsyncClientSession]' = None, comment: 'Optional[Any]' = None) -> 'None'
| Drop a database.
|
| Raises :class:`TypeError` if `name_or_database` is not an instance of
| :class:`str` or :class:`~pymongo.asynchronous.database.AsyncDatabase`.
|
| :param name_or_database: the name of a database to drop, or a
| :class:`~pymongo.asynchronous.database.AsyncDatabase` instance representing the
| database to drop
| :param session: a
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. note:: The :attr:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.write_concern` of
| this client is automatically applied to this operation.
|
| .. versionchanged:: 3.4
| Apply this client's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| eq_props(self) -> 'tuple[tuple[_Address, ...], Optional[str], Optional[str], str]'
|
| get_database(self, name: 'Optional[str]' = None, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'database.AsyncDatabase[_DocumentType]'
| Get a :class:`~pymongo.asynchronous.database.AsyncDatabase` with the given name and
| options.
|
| Useful for creating a :class:`~pymongo.asynchronous.database.AsyncDatabase` with
| different codec options, read preference, and/or write concern from
| this :class:`AsyncMongoClient`.
|
| >>> 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)
|
| :param name: The name of the database - a string. If ``None``
| (the default) the database named in the MongoDB connection URI is
| returned.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is
| used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences`
| for options.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is
| used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is
| used.
|
| .. versionchanged:: 3.5
| The `name` parameter is now optional, defaulting to the database
| named in the MongoDB connection URI.
|
| get_default_database(self, default: 'Optional[str]' = None, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'database.AsyncDatabase[_DocumentType]'
| Get the database named in the MongoDB connection URI.
|
| >>> uri = 'mongodb://host/my_database'
| >>> client = AsyncMongoClient(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.
|
| :param default: the database name to use if no database name
| was provided in the URI.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`AsyncMongoClient` is
| used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`AsyncMongoClient` is used. See :mod:`~pymongo.read_preferences`
| for options.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`AsyncMongoClient` is
| used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`AsyncMongoClient` is
| used.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. 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.
|
| async list_database_names(self, session: 'Optional[client_session.AsyncClientSession]' = None, comment: 'Optional[Any]' = None) -> 'list[str]'
| Get a list of the names of all databases on the connected server.
|
| :param session: a
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionadded:: 3.6
|
| async list_databases(self, session: 'Optional[client_session.AsyncClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'AsyncCommandCursor[dict[str, Any]]'
| Get a cursor over the databases of the connected server.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`AsyncCursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| async with await client.list_databases() as cursor:
| async for database in cursor:
| print(database)
|
| :param session: a
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: Optional parameters of the
| `listDatabases command
| <https://mongodb.com/docs/manual/reference/command/listDatabases/>`_
| can be passed as keyword arguments to this method. The supported
| options differ by server version.
|
|
| :return: An instance of :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor`.
|
| .. versionadded:: 3.6
|
| next = __next__(self) -> 'NoReturn'
|
| async server_info(self, session: 'Optional[client_session.AsyncClientSession]' = None) -> 'dict[str, Any]'
| Get information about the MongoDB server we're connected to.
|
| :param session: a
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| start_session(self, causal_consistency: 'Optional[bool]' = None, default_transaction_options: 'Optional[client_session.TransactionOptions]' = None, snapshot: 'Optional[bool]' = False) -> 'client_session.AsyncClientSession'
| Start a logical session.
|
| This method takes the same parameters as
| :class:`~pymongo.asynchronous.client_session.SessionOptions`. See the
| :mod:`~pymongo.asynchronous.client_session` module for details and examples.
|
| A :class:`~pymongo.asynchronous.client_session.AsyncClientSession` may only be used with
| the AsyncMongoClient that started it. :class:`AsyncClientSession` instances are
| **not thread-safe or fork-safe**. They can only be used by one thread
| or process at a time. A single :class:`AsyncClientSession` cannot be used
| to run multiple operations concurrently.
|
| :return: An instance of :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
|
| .. versionadded:: 3.6
|
| async watch(self, pipeline: 'Optional[_Pipeline]' = None, full_document: 'Optional[str]' = None, resume_after: 'Optional[Mapping[str, Any]]' = None, max_await_time_ms: 'Optional[int]' = None, batch_size: 'Optional[int]' = None, collation: 'Optional[_CollationIn]' = None, start_at_operation_time: 'Optional[Timestamp]' = None, session: 'Optional[client_session.AsyncClientSession]' = None, start_after: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'AsyncChangeStream[_DocumentType]'
| Watch changes on this cluster.
|
| Performs an aggregation with an implicit initial ``$changeStream``
| stage and returns a
| :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` 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.asynchronous.change_stream.AsyncClusterChangeStream` iterable
| blocks until the next change document is returned or an error is
| raised. If the
| :meth:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream.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 AsyncChangeStream 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`_.
|
| :param pipeline: 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.
| :param full_document: The fullDocument to pass as an option
| to the ``$changeStream`` stage. Allowed values: 'updateLookup',
| 'whenAvailable', 'required'. 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.
| :param full_document_before_change: Allowed values: 'whenAvailable'
| and 'required'. Change events may now result in a
| 'fullDocumentBeforeChange' response field.
| :param resume_after: 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.
| :param max_await_time_ms: The maximum time in milliseconds
| for the server to wait for changes before responding to a getMore
| operation.
| :param batch_size: The maximum number of documents to return
| per batch.
| :param collation: The :class:`~pymongo.collation.Collation`
| to use for the aggregation.
| :param start_at_operation_time: 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.
| :param session: a
| :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
| :param start_after: The same as `resume_after` except that
| `start_after` can resume notifications after an invalidate event.
| This option and `resume_after` are mutually exclusive.
| :param comment: A user-provided comment to attach to this
| command.
| :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
| :return: A :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor.
|
| .. versionchanged:: 4.3
| Added `show_expanded_events` parameter.
|
| .. versionchanged:: 4.2
| Added ``full_document_before_change`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.9
| Added the ``start_after`` parameter.
|
| .. versionadded:: 3.7
|
| .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.
|
| .. _change streams specification:
| https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| address
| (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
|
| 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.
|
| 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.
|
| nodes
| Set of all currently connected servers.
|
| .. warning:: When connected to a replica set the value of :attr:`nodes`
| can change over time as :class:`AsyncMongoClient`'s view of the replica
| set changes. :attr:`nodes` can also be an empty set when
| :class:`AsyncMongoClient` is first instantiated and hasn't yet connected
| to any servers, or a network partition causes it to lose connection
| to all servers.
|
| options
| The configuration options for this client.
|
| :return: An instance of :class:`~pymongo.client_options.ClientOptions`.
|
| .. versionadded:: 4.0
|
| 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.
|
| .. versionadded:: 3.0
| AsyncMongoClient gained this property in version 3.0.
|
| 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.
|
| .. versionadded:: 3.0
| AsyncMongoClient gained this property in version 3.0.
|
| topology_description
| The description of the connected MongoDB deployment.
|
| >>> client.topology_description
| <TopologyDescription id: 605a7b04e76489833a7c6113, topology_type: ReplicaSetWithPrimary, servers: [<ServerDescription ('localhost', 27017) server_type: RSPrimary, rtt: 0.0007973677999995488>, <ServerDescription ('localhost', 27018) server_type: RSSecondary, rtt: 0.0005540556000003249>, <ServerDescription ('localhost', 27019) server_type: RSSecondary, rtt: 0.0010367483999999649>]>
| >>> client.topology_description.topology_type_name
| 'ReplicaSetWithPrimary'
|
| Note that the description is periodically updated in the background
| but the returned object itself is immutable. Access this property again
| to get a more recent
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| :return: An instance of
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| .. versionadded:: 4.0
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| HOST = 'localhost'
|
| PORT = 27017
|
| __annotations__ = {'_clients': 'weakref.WeakValueDictionary'}
|
| __iter__ = None
|
| __orig_bases__ = (<class 'pymongo.common.BaseObject'>, typing.Generic[...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.common.BaseObject:
|
| codec_options
| Read only access to the :class:`~bson.codec_options.CodecOptions`
| of this instance.
|
| read_concern
| Read only access to the :class:`~pymongo.read_concern.ReadConcern`
| of this instance.
|
| .. versionadded:: 3.2
|
| read_preference
| Read only access to the read preference of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`read_preference` attribute is now read only.
|
| write_concern
| Read only access to the :class:`~pymongo.write_concern.WriteConcern`
| of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`write_concern` attribute is now read only.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.common.BaseObject:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pymongo.ContextManager
Python Library Documentation: _SpecialGenericAlias in module typing
ContextManager = typing.ContextManager
A generic version of contextlib.AbstractContextManager.
pymongo.CursorType
Python Library Documentation: class CursorType in module pymongo.cursor_shared class CursorType(builtins.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | EXHAUST = 64 | | NON_TAILABLE = 0 | | TAILABLE = 2 | | TAILABLE_AWAIT = 34
pymongo.DESCENDING
Python Library Documentation: int object
class int(object)
| 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
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is equal to the original int.
|
| The ratio is in lowest terms and has a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| is_integer(self, /)
| Returns True. Exists for duck type compatibility with float.is_integer.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes. Default
| is length 1.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False)
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
pymongo.DeleteMany
Python Library Documentation: class DeleteMany in module pymongo.operations
class DeleteMany(_DeleteOp)
| DeleteMany(filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents a delete_many operation.
|
| Method resolution order:
| DeleteMany
| _DeleteOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create a DeleteMany instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the documents to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param namespace: (optional) The namespace in which to delete documents.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _DeleteOp:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _DeleteOp:
|
| __hash__ = None
pymongo.DeleteOne
Python Library Documentation: class DeleteOne in module pymongo.operations
class DeleteOne(_DeleteOp)
| DeleteOne(filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents a delete_one operation.
|
| Method resolution order:
| DeleteOne
| _DeleteOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create a DeleteOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param namespace: (optional) The namespace in which to delete a document.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _DeleteOp:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _DeleteOp:
|
| __hash__ = None
pymongo.GEO2D
Error rendering doc: No Python documentation found for '2d'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pymongo.GEOSPHERE
Error rendering doc: No Python documentation found for '2dsphere'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pymongo.HASHED
Error rendering doc: No Python documentation found for 'hashed'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pymongo.IndexModel
Python Library Documentation: class IndexModel in module pymongo.operations
class IndexModel(builtins.object)
| IndexModel(keys: '_IndexKeyHint', **kwargs: 'Any') -> 'None'
|
| Represents an index to create.
|
| Methods defined here:
|
| __init__(self, keys: '_IndexKeyHint', **kwargs: 'Any') -> 'None'
| Create an Index instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_indexes` and :meth:`~pymongo.collection.Collection.create_indexes`.
|
| Takes either a single key or a list containing (key, direction) pairs
| or keys. If no direction is given, :data:`~pymongo.ASCENDING` will
| be assumed.
| The key(s) must be an instance of :class:`str`, and the direction(s) must
| be one of (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
| :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOSPHERE`,
| :data:`~pymongo.HASHED`, :data:`~pymongo.TEXT`).
|
| Valid options include, but are not limited to:
|
| - `name`: custom name to use for this index - if none is
| given, a name will be generated.
| - `unique`: if ``True``, creates a uniqueness constraint on the index.
| - `background`: if ``True``, this index should be created in the
| background.
| - `sparse`: if ``True``, omit from the index any documents that lack
| the indexed field.
| - `bucketSize`: for use with geoHaystack indexes.
| Number of documents to group together within a certain proximity
| to a given longitude and latitude.
| - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
| collection. MongoDB will automatically delete documents from
| this collection after <int> seconds. The indexed field must
| be a UTC datetime or the data will not expire.
| - `partialFilterExpression`: A document that specifies a filter for
| a partial index.
| - `collation`: An instance of :class:`~pymongo.collation.Collation`
| that specifies the collation to use.
| - `wildcardProjection`: Allows users to include or exclude specific
| field paths from a `wildcard index`_ using the { "$**" : 1} key
| pattern. Requires MongoDB >= 4.2.
| - `hidden`: if ``True``, this index will be hidden from the query
| planner and will not be evaluated as part of query plan
| selection. Requires MongoDB >= 4.4.
|
| See the MongoDB documentation for a full list of supported options by
| server version.
|
| :param keys: a single key or a list containing (key, direction) pairs
| or keys specifying the index to create.
| :param kwargs: any additional index creation
| options (see the above list) should be passed as keyword
| arguments.
|
| .. versionchanged:: 3.11
| Added the ``hidden`` option.
| .. versionchanged:: 3.2
| Added the ``partialFilterExpression`` option to support partial
| indexes.
|
| .. _wildcard index: https://dochub.mongodb.org/core/index-wildcard/
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| document
| An index document suitable for passing to the createIndexes
| command.
pymongo.InsertOne
Python Library Documentation: class InsertOne in module pymongo.operations
class InsertOne(typing.Generic)
| InsertOne(document: '_DocumentType', namespace: 'Optional[str]' = None) -> 'None'
|
| Represents an insert_one operation.
|
| Method resolution order:
| InsertOne
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, document: '_DocumentType', namespace: 'Optional[str]' = None) -> 'None'
| Create an InsertOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param document: The document to insert. If the document is missing an
| _id field one will be added.
| :param namespace: (optional) The namespace in which to insert a document.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __hash__ = None
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pymongo.MAX_SUPPORTED_WIRE_VERSION
Python Library Documentation: int object
class int(object)
| 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
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is equal to the original int.
|
| The ratio is in lowest terms and has a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| is_integer(self, /)
| Returns True. Exists for duck type compatibility with float.is_integer.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes. Default
| is length 1.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False)
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
pymongo.MIN_SUPPORTED_WIRE_VERSION
Python Library Documentation: int object
class int(object)
| 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
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Convert to a string according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
|
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is equal to the original int.
|
| The ratio is in lowest terms and has a positive denominator.
|
| >>> (10).as_integer_ratio()
| (10, 1)
| >>> (-10).as_integer_ratio()
| (-10, 1)
| >>> (0).as_integer_ratio()
| (0, 1)
|
| bit_count(self, /)
| Number of ones in the binary representation of the absolute value of self.
|
| Also known as the population count.
|
| >>> bin(13)
| '0b1101'
| >>> (13).bit_count()
| 3
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| is_integer(self, /)
| Returns True. Exists for duck type compatibility with float.is_integer.
|
| to_bytes(self, /, length=1, byteorder='big', *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes. Default
| is length 1.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder='big', *, signed=False)
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value. Default is to use 'big'.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
pymongo.MongoClient
Python Library Documentation: class MongoClient in module pymongo.synchronous.mongo_client
class MongoClient(pymongo.common.BaseObject, typing.Generic)
| MongoClient(host: 'Optional[Union[str, Sequence[str]]]' = None, port: 'Optional[int]' = None, document_class: 'Optional[Type[_DocumentType]]' = None, tz_aware: 'Optional[bool]' = None, connect: 'Optional[bool]' = None, type_registry: 'Optional[TypeRegistry]' = None, **kwargs: 'Any') -> 'None'
|
| Method resolution order:
| MongoClient
| pymongo.common.BaseObject
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __del__(self) -> 'None'
| Check that this MongoClient has been closed and issue a warning if not.
|
| __enter__(self) -> 'MongoClient[_DocumentType]'
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __getattr__(self, name: 'str') -> 'database.Database[_DocumentType]'
| Get a database by name.
|
| Raises :class:`~pymongo.errors.InvalidName` if an invalid
| database name is used.
|
| :param name: the name of the database to get
|
| __getitem__(self, name: 'str') -> 'database.Database[_DocumentType]'
| Get a database by name.
|
| Raises :class:`~pymongo.errors.InvalidName` if an invalid
| database name is used.
|
| :param name: the name of the database to get
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, host: 'Optional[Union[str, Sequence[str]]]' = None, port: 'Optional[int]' = None, document_class: 'Optional[Type[_DocumentType]]' = None, tz_aware: 'Optional[bool]' = None, connect: 'Optional[bool]' = None, type_registry: 'Optional[TypeRegistry]' = None, **kwargs: 'Any') -> 'None'
| Client for a MongoDB instance, a replica set, or a set of mongoses.
|
| .. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of
| False instead of None.
| For more details, see the relevant section of the PyMongo 4.x migration guide:
| :ref:`pymongo4-migration-direct-connection`.
|
| 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.
|
| Best practice is to call :meth:`MongoClient.close` when the client is no longer needed,
| or use the client in a with statement::
|
| with MongoClient(url) as client:
| # Use client here.
|
| The `host` parameter can be a full `mongodb URI
| <https://dochub.mongodb.org/core/connections>`_, in addition to
| a simple hostname. It can also be a list of hostnames but no more
| than one URI. Any port specified in the host string(s) will override
| the `port` parameter. For username and
| passwords reserved characters like ':', '/', '+' and '@' must be
| percent encoded following RFC 2396::
|
| from urllib.parse 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.md>`_
| 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 ping command is cheap and does not require auth.
| client.admin.command('ping')
| except ConnectionFailure:
| print("Server not available")
|
| .. warning:: When using PyMongo in a multiprocessing context, please
| read `PyMongo multiprocessing <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/mongoclient/#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.
|
| :param host: 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 (but no more than one mongodb
| URI). 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.
| :param port: port number on which to connect
| :param document_class: default class to use for
| documents returned from queries on this client
| :param tz_aware: 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)
| :param connect: If ``True`` (the default), immediately
| begin connecting to MongoDB in the background. Otherwise connect
| on the first operation. The default value is ``False`` when
| running in a Function-as-a-service environment.
| :param type_registry: instance of
| :class:`~bson.codec_options.TypeRegistry` to enable encoding
| and decoding of custom types.
| :param kwargs: **Additional optional parameters available as keyword arguments:**
|
| - `datetime_conversion` (optional): Specifies how UTC datetimes should be decoded
| within BSON. Valid options include 'datetime_ms' to return as a
| DatetimeMS, 'datetime' to return as a datetime.datetime and
| raising a ValueError for out-of-range values, 'datetime_auto' to
| return DatetimeMS objects when the underlying datetime is
| out-of-range and 'datetime_clamp' to clamp to the minimum and
| maximum possible datetimes. Defaults to 'datetime'. See
| `handling out of range datetimes <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times/#handling-out-of-range-datetimes>`_ for details.
| - `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.
| - `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. Can be
| either 0 or None, in which case there is no limit on the number
| of concurrent connections.
| - `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).
| - `maxConnecting` (optional): The maximum number of connections that
| each pool can establish concurrently. Defaults to `2`.
| - `timeoutMS`: (integer or None) Controls how long (in
| milliseconds) the driver will wait when executing an operation
| (including retry attempts) before raising a timeout error.
| ``0`` or ``None`` means no timeout.
| - `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).
| - `heartbeatFrequencyMS`: (optional) The number of milliseconds
| between periodic server checks, or None to accept the default
| frequency of 10 seconds.
| - `serverMonitoringMode`: (optional) The server monitoring mode to use.
| Valid values are the strings: "auto", "stream", "poll". Defaults to "auto".
| - `appname`: (string or None) The name of the application that
| created this MongoClient instance. The server will log this value
| 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. 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.md
| - `retryReads`: (boolean) Whether supported read operations
| executed within this MongoClient will be retried once after a
| network error. 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.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.md>`_.
|
| - `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. For
| Python before 3.14 zstd requires the `backports.zstd <https://pypi.org/project/backports.zstd/>`_
| package. By default no compression is used. Compression support
| must also be enabled on the server. MongoDB 3.6+ supports snappy
| and zlib compression. MongoDB 4.2+ adds support for zstd.
| See `compress network traffic <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/network-compression/#compress-network-traffic>`_ for details.
| - `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 the strings: "standard", "pythonLegacy", "javaLegacy",
| "csharpLegacy", and "unspecified" (the default). New applications
| should consider setting this to "standard" for cross language
| compatibility. See `handling UUID data <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/uuid/#unspecified>`_ for details.
| - `unicode_decode_error_handler`: The error handler to apply when
| a Unicode-related error occurs during BSON decoding that would
| otherwise raise :exc:`UnicodeDecodeError`. Valid options include
| 'strict', 'replace', 'backslashreplace', 'surrogateescape', and
| 'ignore'. Defaults to 'strict'.
| - `srvServiceName`: (string) The SRV service name to use for
| "mongodb+srv://" URIs. Defaults to "mongodb". Use it like so::
|
| MongoClient("mongodb+srv://example.com/?srvServiceName=customname")
| - `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will
| connect to. More specifically, when a "mongodb+srv://" connection string
| resolves to more than srvMaxHosts number of hosts, the client will randomly
| choose an srvMaxHosts sized subset of hosts.
|
|
| | **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`: **DEPRECATED** (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`. 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:: `Customize Server Selection <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/server-selection/#customize-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 negotiates the
| mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server.
| - `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:: `Authentication <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security/authentication/#authentication-mechanisms>`_
|
| | **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
| on-path attackers.
| - `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 on-path attackers.
| - `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. Implies ``tls=True``. Defaults to ``None``.
| - `tlsCRLFile`: A file containing a PEM or DER formatted
| certificate revocation list. Implies ``tls=True``. Defaults to
| ``None``.
| - `tlsCertificateKeyFilePassword`: The password or passphrase for
| decrypting the private key in ``tlsCertificateKeyFile``. Only
| necessary if the private key is encrypted. Defaults to ``None``.
| - `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
| certificate revocation status checking via the OCSP responder
| specified on the server certificate.
| ``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``.
| Defaults to ``False``.
| - `ssl`: (boolean) Alias for ``tls``.
|
| | **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
| `client-side field level encryption <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/security/in-use-encryption/#client-side-field-level-encryption>`_ for an example.
| If a :class:`MongoClient` is configured with
| ``auto_encryption_opts`` and a non-None ``maxPoolSize``, a
| separate internal ``MongoClient`` is created if any of the
| following are true:
|
| - A ``key_vault_client`` is not passed to
| :class:`~pymongo.encryption_options.AutoEncryptionOpts`
| - ``bypass_auto_encrpytion=False`` is passed to
| :class:`~pymongo.encryption_options.AutoEncryptionOpts`
|
| | **Stable API options:**
| | (If not set explicitly, Stable API will not be enabled.)
|
| - `server_api`: A
| :class:`~pymongo.server_api.ServerApi` which configures this
| client to use Stable API. See `versioned API <https://www.mongodb.com/docs/manual/reference/stable-api/#what-is-the-stable-api--and-should-you-use-it->`_ for
| details.
|
| | **Overload retry options:**
|
| - `max_adaptive_retries`: (int) How many retries to allow for overload errors. Defaults to ``2``.
| - `enable_overload_retargeting`: (boolean) Whether overload retargeting is enabled for this client.
| If enabled, server overload errors will cause retry attempts to select a server that has not yet returned an overload error, if possible.
| Defaults to ``False``.
|
| .. seealso:: The MongoDB documentation on `connections <https://dochub.mongodb.org/core/connections>`_.
|
| .. versionchanged:: 4.17
| Added the ``max_adaptive_retries`` and ``enable_overload_retargeting`` URI and keyword arguments.
|
| .. versionchanged:: 4.5
| Added the ``serverMonitoringMode`` keyword argument.
|
| .. versionchanged:: 4.2
| Added the ``timeoutMS`` keyword argument.
|
| .. versionchanged:: 4.0
|
| - Removed the fsync, unlock, is_locked, database_names, and
| close_cursor methods.
| See the :ref:`pymongo4-migration-guide`.
| - Removed the ``waitQueueMultiple`` and ``socketKeepAlive``
| keyword arguments.
| - The default for `uuidRepresentation` was changed from
| ``pythonLegacy`` to ``unspecified``.
| - Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and
| keyword arguments.
|
| .. versionchanged:: 3.12
| Added the ``server_api`` keyword argument.
| The following keyword arguments were deprecated:
|
| - ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor
| of ``tlsCertificateKeyFile``.
|
| .. 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
| `load balancing <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-targets/#replica-sets>`_ 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
| `Copy and Clone Databases <https://www.mongodb.com/docs/database-tools/mongodump/mongodump-examples/#copy-and-clone-databases>`_ 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__
|
| .. versionchanged:: 4.7
| Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`.
|
| .. versionchanged:: 4.9
| The default value of ``connect`` is changed to ``False`` when running in a
| Function-as-a-service environment.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __next__(self) -> 'NoReturn'
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| append_metadata(self, driver_info: 'DriverInfo') -> 'None'
| Appends the given metadata to existing driver metadata.
|
| :param driver_info: a :class:`~pymongo.driver_info.DriverInfo`
|
| .. versionadded:: 4.14
|
| bulk_write(self, models: 'Sequence[_WriteOp]', session: 'Optional[ClientSession]' = None, ordered: 'bool' = True, verbose_results: 'bool' = False, bypass_document_validation: 'Optional[bool]' = None, comment: 'Optional[Any]' = None, let: 'Optional[Mapping[str, Any]]' = None, write_concern: 'Optional[WriteConcern]' = None) -> 'ClientBulkWriteResult'
| Send a batch of write operations, potentially across multiple namespaces, to the server.
|
| Requests are passed as a list of write operation instances (
| :class:`~pymongo.operations.InsertOne`,
| :class:`~pymongo.operations.UpdateOne`,
| :class:`~pymongo.operations.UpdateMany`,
| :class:`~pymongo.operations.ReplaceOne`,
| :class:`~pymongo.operations.DeleteOne`, or
| :class:`~pymongo.operations.DeleteMany`).
|
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| ...
| >>> for doc in db.coll.find({}):
| ... print(doc)
| ...
| {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
| ...
| >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
| >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
| >>> models = [InsertOne(namespace="db.test", document={'y': 1}),
| ... DeleteOne(namespace="db.test", filter={'x': 1}),
| ... InsertOne(namespace="db.coll", document={'y': 2}),
| ... ReplaceOne(namespace="db.test", filter={'w': 1}, replacement={'z': 1}, upsert=True)]
| >>> result = client.bulk_write(models=models)
| >>> result.inserted_count
| 2
| >>> result.deleted_count
| 1
| >>> result.modified_count
| 0
| >>> result.upserted_count
| 1
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
| {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
| ...
| >>> for doc in db.coll.find({}):
| ... print(doc)
| ...
| {'x': 2, '_id': ObjectId('507f1f77bcf86cd799439011')}
| {'y': 2, '_id': ObjectId('507f1f77bcf86cd799439012')}
|
| :param models: A list of write operation instances.
| :param session: (optional) An instance of
| :class:`~pymongo.client_session.ClientSession`.
| :param ordered: If ``True`` (the default), requests will be
| performed on the server serially, in the order provided. If an error
| occurs all remaining operations are aborted. If ``False``, requests
| will be still performed on the server serially, in the order provided,
| but all operations will be attempted even if any errors occur.
| :param verbose_results: If ``True``, detailed results for each
| successful operation will be included in the returned
| :class:`~pymongo.results.ClientBulkWriteResult`. Default is ``False``.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is ``False``.
| :param comment: (optional) A user-provided comment to attach to this
| command.
| :param let: (optional) Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param write_concern: (optional) The write concern to use for this bulk write.
|
| :return: An instance of :class:`~pymongo.results.ClientBulkWriteResult`.
|
| .. seealso:: For more info, see `Client Bulk Write <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/bulk-write/#client-bulk-write-example>`_.
|
| .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_
|
| .. note:: requires MongoDB server version 8.0+.
|
| .. versionadded:: 4.9
|
| close(self) -> 'None'
| Cleanup client resources and disconnect from MongoDB.
|
| 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.
|
| .. versionchanged:: 4.0
| Once closed, the client cannot be used again and any attempt will
| raise :exc:`~pymongo.errors.InvalidOperation`.
|
| .. versionchanged:: 3.6
| End all server sessions created by this client.
|
| drop_database(self, name_or_database: 'Union[str, database.Database[_DocumentTypeArg]]', session: 'Optional[client_session.ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'None'
| Drop a database.
|
| Raises :class:`TypeError` if `name_or_database` is not an instance of
| :class:`str` or :class:`~pymongo.database.Database`.
|
| :param name_or_database: the name of a database to drop, or a
| :class:`~pymongo.database.Database` instance representing the
| database to drop
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. note:: The :attr:`~pymongo.mongo_client.MongoClient.write_concern` of
| this client is automatically applied to this operation.
|
| .. versionchanged:: 3.4
| Apply this client's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| eq_props(self) -> 'tuple[tuple[_Address, ...], Optional[str], Optional[str], str]'
|
| get_database(self, name: 'Optional[str]' = None, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'database.Database[_DocumentType]'
| 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)
|
| :param name: The name of the database - a string. If ``None``
| (the default) the database named in the MongoDB connection URI is
| returned.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`MongoClient` is
| used.
| :param read_preference: 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.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`MongoClient` is
| used.
| :param read_concern: 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.
|
| get_default_database(self, default: 'Optional[str]' = None, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'database.Database[_DocumentType]'
| 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.
|
| :param default: the database name to use if no database name
| was provided in the URI.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`MongoClient` is
| used.
| :param read_preference: 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.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`MongoClient` is
| used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`MongoClient` is
| used.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. 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.
|
| list_database_names(self, session: 'Optional[client_session.ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'list[str]'
| Get a list of the names of all databases on the connected server.
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionadded:: 3.6
|
| list_databases(self, session: 'Optional[client_session.ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'CommandCursor[dict[str, Any]]'
| Get a cursor over the databases of the connected server.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with client.list_databases() as cursor:
| for database in cursor:
| print(database)
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: Optional parameters of the
| `listDatabases command
| <https://mongodb.com/docs/manual/reference/command/listDatabases/>`_
| can be passed as keyword arguments to this method. The supported
| options differ by server version.
|
|
| :return: An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
| .. versionadded:: 3.6
|
| next = __next__(self) -> 'NoReturn'
|
| server_info(self, session: 'Optional[client_session.ClientSession]' = None) -> 'dict[str, Any]'
| Get information about the MongoDB server we're connected to.
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| start_session(self, causal_consistency: 'Optional[bool]' = None, default_transaction_options: 'Optional[client_session.TransactionOptions]' = None, snapshot: 'Optional[bool]' = False) -> 'client_session.ClientSession'
| 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.
|
| 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.
|
| :return: An instance of :class:`~pymongo.client_session.ClientSession`.
|
| .. versionadded:: 3.6
|
| watch(self, pipeline: 'Optional[_Pipeline]' = None, full_document: 'Optional[str]' = None, resume_after: 'Optional[Mapping[str, Any]]' = None, max_await_time_ms: 'Optional[int]' = None, batch_size: 'Optional[int]' = None, collation: 'Optional[_CollationIn]' = None, start_at_operation_time: 'Optional[Timestamp]' = None, session: 'Optional[client_session.ClientSession]' = None, start_after: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'ChangeStream[_DocumentType]'
| 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`_.
|
| :param pipeline: 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.
| :param full_document: The fullDocument to pass as an option
| to the ``$changeStream`` stage. Allowed values: 'updateLookup',
| 'whenAvailable', 'required'. 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.
| :param full_document_before_change: Allowed values: 'whenAvailable'
| and 'required'. Change events may now result in a
| 'fullDocumentBeforeChange' response field.
| :param resume_after: 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.
| :param max_await_time_ms: The maximum time in milliseconds
| for the server to wait for changes before responding to a getMore
| operation.
| :param batch_size: The maximum number of documents to return
| per batch.
| :param collation: The :class:`~pymongo.collation.Collation`
| to use for the aggregation.
| :param start_at_operation_time: 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.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param start_after: The same as `resume_after` except that
| `start_after` can resume notifications after an invalidate event.
| This option and `resume_after` are mutually exclusive.
| :param comment: A user-provided comment to attach to this
| command.
| :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
| :return: A :class:`~pymongo.change_stream.ClusterChangeStream` cursor.
|
| .. versionchanged:: 4.3
| Added `show_expanded_events` parameter.
|
| .. versionchanged:: 4.2
| Added ``full_document_before_change`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.9
| Added the ``start_after`` parameter.
|
| .. versionadded:: 3.7
|
| .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.
|
| .. _change streams specification:
| https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| address
| (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
|
| 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.
|
| 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.
|
| nodes
| 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.
|
| options
| The configuration options for this client.
|
| :return: An instance of :class:`~pymongo.client_options.ClientOptions`.
|
| .. versionadded:: 4.0
|
| 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.
|
| .. versionadded:: 3.0
| MongoClient gained this property in version 3.0.
|
| 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.
|
| .. versionadded:: 3.0
| MongoClient gained this property in version 3.0.
|
| topology_description
| The description of the connected MongoDB deployment.
|
| >>> client.topology_description
| <TopologyDescription id: 605a7b04e76489833a7c6113, topology_type: ReplicaSetWithPrimary, servers: [<ServerDescription ('localhost', 27017) server_type: RSPrimary, rtt: 0.0007973677999995488>, <ServerDescription ('localhost', 27018) server_type: RSSecondary, rtt: 0.0005540556000003249>, <ServerDescription ('localhost', 27019) server_type: RSSecondary, rtt: 0.0010367483999999649>]>
| >>> client.topology_description.topology_type_name
| 'ReplicaSetWithPrimary'
|
| Note that the description is periodically updated in the background
| but the returned object itself is immutable. Access this property again
| to get a more recent
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| :return: An instance of
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| .. versionadded:: 4.0
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| HOST = 'localhost'
|
| PORT = 27017
|
| __annotations__ = {'_clients': 'weakref.WeakValueDictionary'}
|
| __iter__ = None
|
| __orig_bases__ = (<class 'pymongo.common.BaseObject'>, typing.Generic[...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.common.BaseObject:
|
| codec_options
| Read only access to the :class:`~bson.codec_options.CodecOptions`
| of this instance.
|
| read_concern
| Read only access to the :class:`~pymongo.read_concern.ReadConcern`
| of this instance.
|
| .. versionadded:: 3.2
|
| read_preference
| Read only access to the read preference of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`read_preference` attribute is now read only.
|
| write_concern
| Read only access to the :class:`~pymongo.write_concern.WriteConcern`
| of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`write_concern` attribute is now read only.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.common.BaseObject:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pymongo.Optional
Python Library Documentation: _SpecialForm in module typing
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
pymongo.ReadPreference
Python Library Documentation: class ReadPreference in module pymongo.read_preferences
class ReadPreference(builtins.object)
| An enum that defines some commonly used read preference modes.
|
| Apps can also create a custom read preference, for example::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| See `Read and Write Settings <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/configure/#read-and-write-settings>`_ for code examples.
|
| A read preference is used in three cases:
|
| :class:`~pymongo.mongo_client.MongoClient` connected to a single mongod:
|
| - ``PRIMARY``: Queries are allowed if the server is standalone or a replica
| set primary.
| - All other modes allow queries to standalone servers, to a replica set
| primary, or to replica set secondaries.
|
| :class:`~pymongo.mongo_client.MongoClient` initialized with the
| ``replicaSet`` option:
|
| - ``PRIMARY``: Read from the primary. This is the default, and provides the
| strongest consistency. If no primary is available, raise
| :class:`~pymongo.errors.AutoReconnect`.
|
| - ``PRIMARY_PREFERRED``: Read from the primary if available, or if there is
| none, read from a secondary.
|
| - ``SECONDARY``: Read from a secondary. If no secondary is available,
| raise :class:`~pymongo.errors.AutoReconnect`.
|
| - ``SECONDARY_PREFERRED``: Read from a secondary if available, otherwise
| from the primary.
|
| - ``NEAREST``: Read from any member.
|
| :class:`~pymongo.mongo_client.MongoClient` connected to a mongos, with a
| sharded cluster of replica sets:
|
| - ``PRIMARY``: Read from the primary of the shard, or raise
| :class:`~pymongo.errors.OperationFailure` if there is none.
| This is the default.
|
| - ``PRIMARY_PREFERRED``: Read from the primary of the shard, or if there is
| none, read from a secondary of the shard.
|
| - ``SECONDARY``: Read from a secondary of the shard, or raise
| :class:`~pymongo.errors.OperationFailure` if there is none.
|
| - ``SECONDARY_PREFERRED``: Read from a secondary of the shard if available,
| otherwise from the shard primary.
|
| - ``NEAREST``: Read from any shard member.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| NEAREST = Nearest(tag_sets=None, max_staleness=-1, hedge=None)
|
| PRIMARY = Primary()
|
| PRIMARY_PREFERRED = PrimaryPreferred(tag_sets=None, max_staleness=-1, ...
|
| SECONDARY = Secondary(tag_sets=None, max_staleness=-1, hedge=None)
|
| SECONDARY_PREFERRED = SecondaryPreferred(tag_sets=None, max_staleness=...
pymongo.ReplaceOne
Python Library Documentation: class ReplaceOne in module pymongo.operations
class ReplaceOne(typing.Generic)
| ReplaceOne(filter: 'Mapping[str, Any]', replacement: 'Union[_DocumentType, RawBSONDocument]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
|
| Represents a replace_one operation.
|
| Method resolution order:
| ReplaceOne
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, filter: 'Mapping[str, Any]', replacement: 'Union[_DocumentType, RawBSONDocument]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
| Create a ReplaceOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to replace.
| :param replacement: The new document.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
| :param namespace: (optional) The namespace in which to replace a document.
|
| .. versionchanged:: 4.10
| Added ``sort`` option.
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the ``collation`` option.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __hash__ = None
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
pymongo.ReturnDocument
Python Library Documentation: class ReturnDocument in module pymongo.synchronous.collection class ReturnDocument(builtins.object) | An enum used with | :meth:`~pymongo.collection.Collection.find_one_and_replace` and | :meth:`~pymongo.collection.Collection.find_one_and_update`. | | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | AFTER = True | | BEFORE = False
pymongo.TEXT
Error rendering doc: No Python documentation found for 'text'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pymongo.UpdateMany
Python Library Documentation: class UpdateMany in module pymongo.operations
class UpdateMany(_UpdateOp)
| UpdateMany(filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents an update_many operation.
|
| Method resolution order:
| UpdateMany
| _UpdateOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create an UpdateMany instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the documents to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param namespace: (optional) The namespace in which to update documents.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the `hint` option.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the `update`.
| .. versionchanged:: 3.6
| Added the `array_filters` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _UpdateOp:
|
| __eq__(self, other: 'object') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _UpdateOp:
|
| __hash__ = None
pymongo.UpdateOne
Python Library Documentation: class UpdateOne in module pymongo.operations
class UpdateOne(_UpdateOp)
| UpdateOne(filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
|
| Represents an update_one operation.
|
| Method resolution order:
| UpdateOne
| _UpdateOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
| Represents an update_one operation.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param namespace: The namespace in which to update a document.
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
|
| .. versionchanged:: 4.10
| Added ``sort`` option.
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the `hint` option.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the `update`.
| .. versionchanged:: 3.6
| Added the `array_filters` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _UpdateOp:
|
| __eq__(self, other: 'object') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _UpdateOp:
|
| __hash__ = None
pymongo.WriteConcern
Python Library Documentation: class WriteConcern in module pymongo.write_concern class WriteConcern(builtins.object) | WriteConcern(w: 'Optional[Union[int, str]]' = None, wtimeout: 'Optional[int]' = None, j: 'Optional[bool]' = None, fsync: 'Optional[bool]' = None) -> 'None' | | WriteConcern | | :param w: (integer or string) Used with replication, write operations | will block until they have been replicated to the specified number | or tagged set of servers. `w=<integer>` always includes the replica | set primary (e.g. w=3 means write to the primary and wait until | replicated to **two** secondaries). **w=0 disables acknowledgement | of write operations and can not be used with other write concern | options.** | :param wtimeout: (integer) **DEPRECATED** 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. | :param j: If ``True`` block until write operations have been committed | to the journal. Cannot be used in combination with `fsync`. Write | operations will fail with an exception if this option is used when | the server is running without journaling. | :param 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`. | | | .. versionchanged:: 4.7 | Deprecated parameter ``wtimeout``, use :meth:`~pymongo.timeout`. | | Methods defined here: | | __eq__(self, other: 'Any') -> 'bool' | Return self==value. | | __init__(self, w: 'Optional[Union[int, str]]' = None, wtimeout: 'Optional[int]' = None, j: 'Optional[bool]' = None, fsync: 'Optional[bool]' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | __ne__(self, other: 'Any') -> 'bool' | Return self!=value. | | __repr__(self) -> 'str' | Return repr(self). | | ---------------------------------------------------------------------- | Readonly properties defined here: | | acknowledged | If ``True`` write operations will wait for acknowledgement before | returning. | | document | The document representation of this write concern. | | .. note:: | :class:`WriteConcern` is immutable. Mutating the value of | :attr:`document` does not mutate this :class:`WriteConcern`. | | is_server_default | Does this WriteConcern match the server default. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
pymongo.annotations
Python Library Documentation: _Feature in module __future__ object class _Feature(builtins.object) | _Feature(optionalRelease, mandatoryRelease, compiler_flag) | | Methods defined here: | | __init__(self, optionalRelease, mandatoryRelease, compiler_flag) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | getMandatoryRelease(self) | Return release in which this feature will become mandatory. | | This is a 5-tuple, of the same form as sys.version_info, or, if | the feature was dropped, or the release date is undetermined, is None. | | getOptionalRelease(self) | Return first release in which this feature was recognized. | | This is a 5-tuple, of the same form as sys.version_info. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
pymongo.asynchronous
Python Library Documentation: package pymongo.asynchronous in pymongo
NAME
pymongo.asynchronous
PACKAGE CONTENTS
aggregation
auth
auth_aws
auth_oidc
bulk
change_stream
client_bulk
client_session
collection
command_cursor
cursor
cursor_base
database
encryption
helpers
mongo_client
monitor
network
pool
server
settings
srv_resolver
topology
uri_parser
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\asynchronous\__init__.py
pymongo.change_stream
Python Library Documentation: module pymongo.change_stream in pymongo
NAME
pymongo.change_stream - Watch changes on a collection, a database, or the entire cluster.
CLASSES
typing.Generic(builtins.object)
pymongo.synchronous.change_stream.ChangeStream
pymongo.synchronous.change_stream.CollectionChangeStream
pymongo.synchronous.change_stream.DatabaseChangeStream
pymongo.synchronous.change_stream.ClusterChangeStream
class ChangeStream(typing.Generic)
| ChangeStream(target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
|
| The internal abstract base class for change stream cursors.
|
| Should not be called directly by application developers. Use
| :meth:`pymongo.collection.Collection.watch`,
| :meth:`pymongo.database.Database.watch`, or
| :meth:`pymongo.mongo_client.MongoClient.watch` instead.
|
| .. versionadded:: 3.6
| .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.
|
| Method resolution order:
| ChangeStream
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'ChangeStream[_DocumentType]'
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __init__(self, target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'ChangeStream[_DocumentType]'
|
| __next__ = next(self) -> '_DocumentType'
|
| close(self) -> 'None'
| Close this ChangeStream.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| This method blocks until the next change document is returned or an
| unrecoverable error is raised. This method is used when iterating over
| all changes in the cursor. For example::
|
| try:
| resume_token = None
| pipeline = [{'$match': {'operationType': 'insert'}}]
| with db.collection.watch(pipeline) as stream:
| for insert_change in stream:
| print(insert_change)
| resume_token = stream.resume_token
| except pymongo.errors.PyMongoError:
| # The ChangeStream encountered an unrecoverable error or the
| # resume attempt failed to recreate the cursor.
| if resume_token is None:
| # There is no usable resume token because there was a
| # failure during ChangeStream initialization.
| logging.error('...')
| else:
| # Use the interrupted ChangeStream's resume token to create
| # a new ChangeStream. The new stream will continue from the
| # last seen insert change without missing any events.
| with db.collection.watch(
| pipeline, resume_after=resume_token) as stream:
| for insert_change in stream:
| print(insert_change)
|
| Raises :exc:`StopIteration` if this ChangeStream is closed.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next change document without waiting
| indefinitely for the next change. For example::
|
| with db.collection.watch() as stream:
| while stream.alive:
| change = stream.try_next()
| # Note that the ChangeStream's resume token may be updated
| # even when no changes are returned.
| print("Current resume token: %r" % (stream.resume_token,))
| if change is not None:
| print("Change document: %r" % (change,))
| continue
| # We end up here when there are no recent changes.
| # Sleep for a while before trying again to avoid flooding
| # the server with getMore requests when no changes are
| # available.
| time.sleep(10)
|
| If no change document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there have been no changes) then ``None`` is returned.
|
| :return: The next change document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 3.8
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| alive
| Does this cursor have the potential to return more data?
|
| .. note:: Even if :attr:`alive` is ``True``, :meth:`next` can raise
| :exc:`StopIteration` and :meth:`try_next` can return ``None``.
|
| .. versionadded:: 3.8
|
| resume_token
| The cached resume token that will be used to resume after the most
| recently returned change.
|
| .. versionadded:: 3.9
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ClusterChangeStream(DatabaseChangeStream)
| ClusterChangeStream(target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
|
| A change stream that watches changes on all collections in the cluster.
|
| Should not be called directly by application developers. Use
| helper method :meth:`pymongo.mongo_client.MongoClient.watch` instead.
|
| .. versionadded:: 3.7
|
| Method resolution order:
| ClusterChangeStream
| DatabaseChangeStream
| ChangeStream
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (pymongo.synchronous.change_stream.DatabaseChangeStre...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from ChangeStream:
|
| __enter__(self) -> 'ChangeStream[_DocumentType]'
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __init__(self, target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'ChangeStream[_DocumentType]'
|
| __next__ = next(self) -> '_DocumentType'
|
| close(self) -> 'None'
| Close this ChangeStream.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| This method blocks until the next change document is returned or an
| unrecoverable error is raised. This method is used when iterating over
| all changes in the cursor. For example::
|
| try:
| resume_token = None
| pipeline = [{'$match': {'operationType': 'insert'}}]
| with db.collection.watch(pipeline) as stream:
| for insert_change in stream:
| print(insert_change)
| resume_token = stream.resume_token
| except pymongo.errors.PyMongoError:
| # The ChangeStream encountered an unrecoverable error or the
| # resume attempt failed to recreate the cursor.
| if resume_token is None:
| # There is no usable resume token because there was a
| # failure during ChangeStream initialization.
| logging.error('...')
| else:
| # Use the interrupted ChangeStream's resume token to create
| # a new ChangeStream. The new stream will continue from the
| # last seen insert change without missing any events.
| with db.collection.watch(
| pipeline, resume_after=resume_token) as stream:
| for insert_change in stream:
| print(insert_change)
|
| Raises :exc:`StopIteration` if this ChangeStream is closed.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next change document without waiting
| indefinitely for the next change. For example::
|
| with db.collection.watch() as stream:
| while stream.alive:
| change = stream.try_next()
| # Note that the ChangeStream's resume token may be updated
| # even when no changes are returned.
| print("Current resume token: %r" % (stream.resume_token,))
| if change is not None:
| print("Change document: %r" % (change,))
| continue
| # We end up here when there are no recent changes.
| # Sleep for a while before trying again to avoid flooding
| # the server with getMore requests when no changes are
| # available.
| time.sleep(10)
|
| If no change document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there have been no changes) then ``None`` is returned.
|
| :return: The next change document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 3.8
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ChangeStream:
|
| alive
| Does this cursor have the potential to return more data?
|
| .. note:: Even if :attr:`alive` is ``True``, :meth:`next` can raise
| :exc:`StopIteration` and :meth:`try_next` can return ``None``.
|
| .. versionadded:: 3.8
|
| resume_token
| The cached resume token that will be used to resume after the most
| recently returned change.
|
| .. versionadded:: 3.9
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ChangeStream:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class CollectionChangeStream(ChangeStream)
| CollectionChangeStream(target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
|
| A change stream that watches changes on a single collection.
|
| Should not be called directly by application developers. Use
| helper method :meth:`pymongo.collection.Collection.watch` instead.
|
| .. versionadded:: 3.7
|
| Method resolution order:
| CollectionChangeStream
| ChangeStream
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'_target': 'Collection[_DocumentType]'}
|
| __orig_bases__ = (pymongo.synchronous.change_stream.ChangeStream[~_Doc...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from ChangeStream:
|
| __enter__(self) -> 'ChangeStream[_DocumentType]'
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __init__(self, target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'ChangeStream[_DocumentType]'
|
| __next__ = next(self) -> '_DocumentType'
|
| close(self) -> 'None'
| Close this ChangeStream.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| This method blocks until the next change document is returned or an
| unrecoverable error is raised. This method is used when iterating over
| all changes in the cursor. For example::
|
| try:
| resume_token = None
| pipeline = [{'$match': {'operationType': 'insert'}}]
| with db.collection.watch(pipeline) as stream:
| for insert_change in stream:
| print(insert_change)
| resume_token = stream.resume_token
| except pymongo.errors.PyMongoError:
| # The ChangeStream encountered an unrecoverable error or the
| # resume attempt failed to recreate the cursor.
| if resume_token is None:
| # There is no usable resume token because there was a
| # failure during ChangeStream initialization.
| logging.error('...')
| else:
| # Use the interrupted ChangeStream's resume token to create
| # a new ChangeStream. The new stream will continue from the
| # last seen insert change without missing any events.
| with db.collection.watch(
| pipeline, resume_after=resume_token) as stream:
| for insert_change in stream:
| print(insert_change)
|
| Raises :exc:`StopIteration` if this ChangeStream is closed.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next change document without waiting
| indefinitely for the next change. For example::
|
| with db.collection.watch() as stream:
| while stream.alive:
| change = stream.try_next()
| # Note that the ChangeStream's resume token may be updated
| # even when no changes are returned.
| print("Current resume token: %r" % (stream.resume_token,))
| if change is not None:
| print("Change document: %r" % (change,))
| continue
| # We end up here when there are no recent changes.
| # Sleep for a while before trying again to avoid flooding
| # the server with getMore requests when no changes are
| # available.
| time.sleep(10)
|
| If no change document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there have been no changes) then ``None`` is returned.
|
| :return: The next change document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 3.8
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ChangeStream:
|
| alive
| Does this cursor have the potential to return more data?
|
| .. note:: Even if :attr:`alive` is ``True``, :meth:`next` can raise
| :exc:`StopIteration` and :meth:`try_next` can return ``None``.
|
| .. versionadded:: 3.8
|
| resume_token
| The cached resume token that will be used to resume after the most
| recently returned change.
|
| .. versionadded:: 3.9
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ChangeStream:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class DatabaseChangeStream(ChangeStream)
| DatabaseChangeStream(target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
|
| A change stream that watches changes on all collections in a database.
|
| Should not be called directly by application developers. Use
| helper method :meth:`pymongo.database.Database.watch` instead.
|
| .. versionadded:: 3.7
|
| Method resolution order:
| DatabaseChangeStream
| ChangeStream
| typing.Generic
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {'_target': 'Database[_DocumentType]'}
|
| __orig_bases__ = (pymongo.synchronous.change_stream.ChangeStream[~_Doc...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from ChangeStream:
|
| __enter__(self) -> 'ChangeStream[_DocumentType]'
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __init__(self, target: 'Union[MongoClient[_DocumentType], Database[_DocumentType], Collection[_DocumentType]]', pipeline: 'Optional[_Pipeline]', full_document: 'Optional[str]', resume_after: 'Optional[Mapping[str, Any]]', max_await_time_ms: 'Optional[int]', batch_size: 'Optional[int]', collation: 'Optional[_CollationIn]', start_at_operation_time: 'Optional[Timestamp]', session: 'Optional[ClientSession]', start_after: 'Optional[Mapping[str, Any]]', comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> 'ChangeStream[_DocumentType]'
|
| __next__ = next(self) -> '_DocumentType'
|
| close(self) -> 'None'
| Close this ChangeStream.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| This method blocks until the next change document is returned or an
| unrecoverable error is raised. This method is used when iterating over
| all changes in the cursor. For example::
|
| try:
| resume_token = None
| pipeline = [{'$match': {'operationType': 'insert'}}]
| with db.collection.watch(pipeline) as stream:
| for insert_change in stream:
| print(insert_change)
| resume_token = stream.resume_token
| except pymongo.errors.PyMongoError:
| # The ChangeStream encountered an unrecoverable error or the
| # resume attempt failed to recreate the cursor.
| if resume_token is None:
| # There is no usable resume token because there was a
| # failure during ChangeStream initialization.
| logging.error('...')
| else:
| # Use the interrupted ChangeStream's resume token to create
| # a new ChangeStream. The new stream will continue from the
| # last seen insert change without missing any events.
| with db.collection.watch(
| pipeline, resume_after=resume_token) as stream:
| for insert_change in stream:
| print(insert_change)
|
| Raises :exc:`StopIteration` if this ChangeStream is closed.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next change document without waiting
| indefinitely for the next change. For example::
|
| with db.collection.watch() as stream:
| while stream.alive:
| change = stream.try_next()
| # Note that the ChangeStream's resume token may be updated
| # even when no changes are returned.
| print("Current resume token: %r" % (stream.resume_token,))
| if change is not None:
| print("Change document: %r" % (change,))
| continue
| # We end up here when there are no recent changes.
| # Sleep for a while before trying again to avoid flooding
| # the server with getMore requests when no changes are
| # available.
| time.sleep(10)
|
| If no change document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there have been no changes) then ``None`` is returned.
|
| :return: The next change document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 3.8
|
| ----------------------------------------------------------------------
| Readonly properties inherited from ChangeStream:
|
| alive
| Does this cursor have the potential to return more data?
|
| .. note:: Even if :attr:`alive` is ``True``, :meth:`next` can raise
| :exc:`StopIteration` and :meth:`try_next` can return ``None``.
|
| .. versionadded:: 3.8
|
| resume_token
| The cached resume token that will be used to resume after the most
| recently returned change.
|
| .. versionadded:: 3.9
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ChangeStream:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
__all__ = ['ChangeStream', 'ClusterChangeStream', 'CollectionChangeStr...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\change_stream.py
pymongo.client_options
Python Library Documentation: module pymongo.client_options in pymongo
NAME
pymongo.client_options - Tools to parse mongo client options.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
ClientOptions
class ClientOptions(builtins.object)
| ClientOptions(username: 'str', password: 'str', database: 'Optional[str]', options: 'Mapping[str, Any]', is_sync: 'bool' = True)
|
| Read only configuration options for an AsyncMongoClient/MongoClient.
|
| Should not be instantiated directly by application developers. Access
| a client's options via :attr:`pymongo.mongo_client.AsyncMongoClient.options` or :attr:`pymongo.mongo_client.MongoClient.options`
| instead.
|
| Methods defined here:
|
| __init__(self, username: 'str', password: 'str', database: 'Optional[str]', options: 'Mapping[str, Any]', is_sync: 'bool' = True)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| auto_encryption_opts
| A :class:`~pymongo.encryption.AutoEncryptionOpts` or None.
|
| codec_options
| A :class:`~bson.codec_options.CodecOptions` instance.
|
| connect
| Whether to begin discovering a MongoDB topology automatically.
|
| direct_connection
| Whether to connect to the deployment in 'Single' topology.
|
| enable_overload_retargeting
| The configured enableOverloadRetargeting option.
|
| .. versionadded:: 4.17
|
| event_listeners
| The event listeners registered for this client.
|
| See :mod:`~pymongo.monitoring` for details.
|
| .. versionadded:: 4.0
|
| heartbeat_frequency
| The monitoring frequency in seconds.
|
| load_balanced
| True if the client was configured to connect to a load balancer.
|
| local_threshold_ms
| The local threshold for this instance.
|
| max_adaptive_retries
| The configured maxAdaptiveRetries option.
|
| .. versionadded:: 4.17
|
| pool_options
| A :class:`~pymongo.pool.PoolOptions` instance.
|
| read_concern
| A :class:`~pymongo.read_concern.ReadConcern` instance.
|
| read_preference
| A read preference instance.
|
| replica_set_name
| Replica set name or None.
|
| retry_reads
| If this instance should retry supported read operations.
|
| retry_writes
| If this instance should retry supported write operations.
|
| server_monitoring_mode
| The configured serverMonitoringMode option.
|
| .. versionadded:: 4.5
|
| server_selection_timeout
| The server selection timeout for this instance in seconds.
|
| server_selector
|
| timeout
| The configured timeoutMS converted to seconds, or None.
|
| .. versionadded:: 4.2
|
| write_concern
| A :class:`~pymongo.write_concern.WriteConcern` instance.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\client_options.py
pymongo.client_session
Python Library Documentation: module pymongo.client_session in pymongo
NAME
pymongo.client_session - Logical sessions for ordering sequential operations.
DESCRIPTION
.. versionadded:: 3.6
Causally Consistent Reads
=========================
.. code-block:: python
with client.start_session(causal_consistency=True) as session:
collection = client.db.collection
collection.update_one({"_id": 1}, {"$set": {"x": 10}}, session=session)
secondary_c = collection.with_options(read_preference=ReadPreference.SECONDARY)
# A secondary read waits for replication of the write.
secondary_c.find_one({"_id": 1}, session=session)
If `causal_consistency` is True (the default), read operations that use
the session are causally after previous read and write operations. Using a
causally consistent session, an application can read its own writes and is
guaranteed monotonic reads, even when reading from replica set secondaries.
.. seealso:: The MongoDB documentation on `causal-consistency <https://dochub.mongodb.org/core/causal-consistency>`_.
.. _transactions-ref:
Transactions
============
.. versionadded:: 3.7
MongoDB 4.0 adds support for transactions on replica set primaries. A
transaction is associated with a :class:`ClientSession`. To start a transaction
on a session, use :meth:`ClientSession.start_transaction` in a with-statement.
Then, execute an operation within the transaction by passing the session to the
operation:
.. code-block:: python
orders = client.db.orders
inventory = client.db.inventory
with client.start_session() as session:
with session.start_transaction():
orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
inventory.update_one(
{"sku": "abc123", "qty": {"$gte": 100}},
{"$inc": {"qty": -100}},
session=session,
)
Upon normal completion of ``with session.start_transaction()`` block, the
transaction automatically calls :meth:`ClientSession.commit_transaction`.
If the block exits with an exception, the transaction automatically calls
:meth:`ClientSession.abort_transaction`.
In general, multi-document transactions only support read/write (CRUD)
operations on existing collections. However, MongoDB 4.4 adds support for
creating collections and indexes with some limitations, including an
insert operation that would result in the creation of a new collection.
For a complete description of all the supported and unsupported operations
see the `MongoDB server's documentation for transactions
<http://dochub.mongodb.org/core/transactions>`_.
A session may only have a single active transaction at a time, multiple
transactions on the same session can be executed in sequence.
Sharded Transactions
^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.9
PyMongo 3.9 adds support for transactions on sharded clusters running MongoDB
>=4.2. Sharded transactions have the same API as replica set transactions.
When running a transaction against a sharded cluster, the session is
pinned to the mongos server selected for the first operation in the
transaction. All subsequent operations that are part of the same transaction
are routed to the same mongos server. When the transaction is completed, by
running either commitTransaction or abortTransaction, the session is unpinned.
.. seealso:: The MongoDB documentation on `transactions <https://dochub.mongodb.org/core/transactions>`_.
.. _snapshot-reads-ref:
Snapshot Reads
==============
.. versionadded:: 3.12
MongoDB 5.0 adds support for snapshot reads. Snapshot reads are requested by
passing the ``snapshot`` option to
:meth:`~pymongo.mongo_client.MongoClient.start_session`.
If ``snapshot`` is True, all read operations that use this session read data
from the same snapshot timestamp. The server chooses the latest
majority-committed snapshot timestamp when executing the first read operation
using the session. Subsequent reads on this session read from the same
snapshot timestamp. Snapshot reads are also supported when reading from
replica set secondaries.
.. code-block:: python
# Each read using this session reads data from the same point in time.
with client.start_session(snapshot=True) as session:
order = orders.find_one({"sku": "abc123"}, session=session)
inventory = inventory.find_one({"sku": "abc123"}, session=session)
Snapshot Reads Limitations
^^^^^^^^^^^^^^^^^^^^^^^^^^
Snapshot reads sessions are incompatible with ``causal_consistency=True``.
Only the following read operations are supported in a snapshot reads session:
- :meth:`~pymongo.collection.Collection.find`
- :meth:`~pymongo.collection.Collection.find_one`
- :meth:`~pymongo.collection.Collection.aggregate`
- :meth:`~pymongo.collection.Collection.count_documents`
- :meth:`~pymongo.collection.Collection.distinct` (on unsharded collections)
Classes
=======
CLASSES
builtins.object
pymongo.synchronous.client_session.ClientSession
pymongo.synchronous.client_session.SessionOptions
pymongo.synchronous.client_session.TransactionOptions
class ClientSession(builtins.object)
| ClientSession(client: 'MongoClient[Any]', server_session: 'Any', options: 'SessionOptions', implicit: 'bool') -> 'None'
|
| A session for ordering sequential operations.
|
| :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.
|
| Should not be initialized directly by application developers - to create a
| :class:`ClientSession`, call
| :meth:`~pymongo.mongo_client.MongoClient.start_session`.
|
| Methods defined here:
|
| __copy__(self) -> 'NoReturn'
|
| __enter__(self) -> 'ClientSession'
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| __init__(self, client: 'MongoClient[Any]', server_session: 'Any', options: 'SessionOptions', implicit: 'bool') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| abort_transaction(self) -> 'None'
| Abort a multi-statement transaction.
|
| .. versionadded:: 3.7
|
| advance_cluster_time(self, cluster_time: 'Mapping[str, Any]') -> 'None'
| Update the cluster time for this session.
|
| :param cluster_time: The
| :data:`~pymongo.client_session.ClientSession.cluster_time` from
| another `ClientSession` instance.
|
| advance_operation_time(self, operation_time: 'Timestamp') -> 'None'
| Update the operation time for this session.
|
| :param operation_time: The
| :data:`~pymongo.client_session.ClientSession.operation_time` from
| another `ClientSession` instance.
|
| bind(self, end_session: 'bool' = True) -> '_BoundSessionContext'
| Bind this session so it is implicitly passed to all database operations within the returned context.
|
| .. code-block:: python
|
| with client.start_session() as s:
| with s.bind():
| # session=s is passed implicitly
| client.db.collection.insert_one({"x": 1})
|
| :param end_session: Whether to end the session on exiting the returned context. Defaults to True.
| If set to False, :meth:`~pymongo.client_session.ClientSession.end_session()` must be called
| once the session is no longer used.
|
| .. versionadded:: 4.17
|
| commit_transaction(self) -> 'None'
| Commit a multi-statement transaction.
|
| .. versionadded:: 3.7
|
| end_session(self) -> 'None'
| Finish this session. If a transaction has started, abort it.
|
| It is an error to use the session after the session has ended.
|
| start_transaction(self, read_concern: 'Optional[ReadConcern]' = None, write_concern: 'Optional[WriteConcern]' = None, read_preference: 'Optional[_ServerMode]' = None, max_commit_time_ms: 'Optional[int]' = None) -> 'ContextManager[Any]'
| Start a multi-statement transaction.
|
| Takes the same arguments as :class:`TransactionOptions`.
|
| .. versionchanged:: 3.9
| Added the ``max_commit_time_ms`` option.
|
| .. versionadded:: 3.7
|
| with_transaction(self, callback: 'Callable[[ClientSession], _T]', read_concern: 'Optional[ReadConcern]' = None, write_concern: 'Optional[WriteConcern]' = None, read_preference: 'Optional[_ServerMode]' = None, max_commit_time_ms: 'Optional[int]' = None) -> '_T'
| Execute a callback in a transaction.
|
| This method starts a transaction on this session, executes ``callback``
| once, and then commits the transaction. For example::
|
| def callback(session):
| orders = session.client.db.orders
| inventory = session.client.db.inventory
| orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
| inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
| {"$inc": {"qty": -100}}, session=session)
|
| with client.start_session() as session:
| session.with_transaction(callback)
|
| To pass arbitrary arguments to the ``callback``, wrap your callable
| with a ``lambda`` like this::
|
| def callback(session, custom_arg, custom_kwarg=None):
| # Transaction operations...
|
| with client.start_session() as session:
| session.with_transaction(
| lambda s: callback(s, "custom_arg", custom_kwarg=1))
|
| In the event of an exception, ``with_transaction`` may retry the commit
| or the entire transaction, therefore ``callback`` may be invoked
| multiple times by a single call to ``with_transaction``. Developers
| should be mindful of this possibility when writing a ``callback`` that
| modifies application state or has any other side-effects.
| Note that even when the ``callback`` is invoked multiple times,
| ``with_transaction`` ensures that the transaction will be committed
| at-most-once on the server.
|
| The ``callback`` should not attempt to start new transactions, but
| should simply run operations meant to be contained within a
| transaction. The ``callback`` should also not commit the transaction;
| this is handled automatically by ``with_transaction``. If the
| ``callback`` does commit or abort the transaction without error,
| however, ``with_transaction`` will return without taking further
| action.
|
| :class:`ClientSession` instances are **not thread-safe or fork-safe**.
| Consequently, the ``callback`` must not attempt to execute multiple
| operations concurrently.
|
| When ``callback`` raises an exception, ``with_transaction``
| automatically aborts the current transaction. When ``callback`` or
| :meth:`~ClientSession.commit_transaction` raises an exception that
| includes the ``"TransientTransactionError"`` error label,
| ``with_transaction`` starts a new transaction and re-executes
| the ``callback``.
|
| The ``callback`` MUST NOT silently handle command errors
| without allowing such errors to propagate. Command errors may abort the
| transaction on the server, and an attempt to commit the transaction will
| be rejected with a ``NoSuchTransaction`` error. For more information see
| the `transactions specification`_.
|
| When :meth:`~ClientSession.commit_transaction` raises an exception with
| the ``"UnknownTransactionCommitResult"`` error label,
| ``with_transaction`` retries the commit until the result of the
| transaction is known.
|
| This method will cease retrying after 120 seconds has elapsed. This
| timeout is not configurable and any exception raised by the
| ``callback`` or by :meth:`ClientSession.commit_transaction` after the
| timeout is reached will be re-raised. Applications that desire a
| different timeout duration should not use this method.
|
| :param callback: The callable ``callback`` to run inside a transaction.
| The callable must accept a single argument, this session. Note,
| under certain error conditions the callback may be run multiple
| times.
| :param read_concern: The
| :class:`~pymongo.read_concern.ReadConcern` to use for this
| transaction.
| :param write_concern: The
| :class:`~pymongo.write_concern.WriteConcern` to use for this
| transaction.
| :param read_preference: The read preference to use for this
| transaction. If ``None`` (the default) the :attr:`read_preference`
| of this :class:`Database` is used. See
| :mod:`~pymongo.read_preferences` for options.
|
| :return: The return value of the ``callback``.
|
| .. versionadded:: 3.9
|
| .. _transactions specification:
| https://github.com/mongodb/specifications/blob/master/source/transactions-convenient-api/transactions-convenient-api.md#handling-errors-inside-the-callback
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| client
| The :class:`~pymongo.mongo_client.MongoClient` this session was
| created from.
|
| cluster_time
| The cluster time returned by the last operation executed
| in this session.
|
| has_ended
| True if this session is finished.
|
| in_transaction
| True if this session has an active multi-statement transaction.
|
| .. versionadded:: 3.10
|
| operation_time
| The operation time returned by the last operation executed
| in this session.
|
| options
| The :class:`SessionOptions` this session was created with.
|
| session_id
| A BSON document, the opaque server session identifier.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class SessionOptions(builtins.object)
| SessionOptions(causal_consistency: 'Optional[bool]' = None, default_transaction_options: 'Optional[TransactionOptions]' = None, snapshot: 'Optional[bool]' = False) -> 'None'
|
| Options for a new :class:`ClientSession`.
|
| :param causal_consistency: If True, read operations are causally
| ordered within the session. Defaults to True when the ``snapshot``
| option is ``False``.
| :param default_transaction_options: The default
| TransactionOptions to use for transactions started on this session.
| :param snapshot: If True, then all reads performed using this
| session will read from the same snapshot. This option is incompatible
| with ``causal_consistency=True``. Defaults to ``False``.
|
| .. versionchanged:: 3.12
| Added the ``snapshot`` parameter.
|
| Methods defined here:
|
| __init__(self, causal_consistency: 'Optional[bool]' = None, default_transaction_options: 'Optional[TransactionOptions]' = None, snapshot: 'Optional[bool]' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| causal_consistency
| Whether causal consistency is configured.
|
| default_transaction_options
| The default TransactionOptions to use for transactions started on
| this session.
|
| .. versionadded:: 3.7
|
| snapshot
| Whether snapshot reads are configured.
|
| .. versionadded:: 3.12
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class TransactionOptions(builtins.object)
| TransactionOptions(read_concern: 'Optional[ReadConcern]' = None, write_concern: 'Optional[WriteConcern]' = None, read_preference: 'Optional[_ServerMode]' = None, max_commit_time_ms: 'Optional[int]' = None) -> 'None'
|
| Options for :meth:`ClientSession.start_transaction`.
|
| :param read_concern: The
| :class:`~pymongo.read_concern.ReadConcern` to use for this transaction.
| If ``None`` (the default) the :attr:`read_preference` of
| the :class:`MongoClient` is used.
| :param write_concern: The
| :class:`~pymongo.write_concern.WriteConcern` to use for this
| transaction. If ``None`` (the default) the :attr:`read_preference` of
| the :class:`MongoClient` is used.
| :param read_preference: 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. Transactions which read must use
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
| :param max_commit_time_ms: The maximum amount of time to allow a
| single commitTransaction command to run. This option is an alias for
| maxTimeMS option on the commitTransaction command. If ``None`` (the
| default) maxTimeMS is not used.
|
| .. versionchanged:: 3.9
| Added the ``max_commit_time_ms`` option.
|
| .. versionadded:: 3.7
|
| Methods defined here:
|
| __init__(self, read_concern: 'Optional[ReadConcern]' = None, write_concern: 'Optional[WriteConcern]' = None, read_preference: 'Optional[_ServerMode]' = None, max_commit_time_ms: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| max_commit_time_ms
| The maxTimeMS to use when running a commitTransaction command.
|
| .. versionadded:: 3.9
|
| read_concern
| This transaction's :class:`~pymongo.read_concern.ReadConcern`.
|
| read_preference
| This transaction's :class:`~pymongo.read_preferences.ReadPreference`.
|
| write_concern
| This transaction's :class:`~pymongo.write_concern.WriteConcern`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
__all__ = ['ClientSession', 'SessionOptions', 'TransactionOptions']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\client_session.py
pymongo.collation
Python Library Documentation: module pymongo.collation in pymongo
NAME
pymongo.collation - Tools for working with `collations`_.
DESCRIPTION
.. _collations: https://www.mongodb.com/docs/manual/reference/collation/
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
Collation
CollationAlternate
CollationCaseFirst
CollationMaxVariable
CollationStrength
class Collation(builtins.object)
| Collation(locale: 'str', caseLevel: 'Optional[bool]' = None, caseFirst: 'Optional[str]' = None, strength: 'Optional[int]' = None, numericOrdering: 'Optional[bool]' = None, alternate: 'Optional[str]' = None, maxVariable: 'Optional[str]' = None, normalization: 'Optional[bool]' = None, backwards: 'Optional[bool]' = None, **kwargs: 'Any') -> 'None'
|
| Collation
|
| :param locale: (string) The locale of the collation. This should be a string
| that identifies an `ICU locale ID` exactly. For example, ``en_US`` is
| valid, but ``en_us`` and ``en-US`` are not. Consult the MongoDB
| documentation for a list of supported locales.
| :param caseLevel: (optional) If ``True``, turn on case sensitivity if
| `strength` is 1 or 2 (case sensitivity is implied if `strength` is
| greater than 2). Defaults to ``False``.
| :param caseFirst: (optional) Specify that either uppercase or lowercase
| characters take precedence. Must be one of the following values:
|
| * :data:`~CollationCaseFirst.UPPER`
| * :data:`~CollationCaseFirst.LOWER`
| * :data:`~CollationCaseFirst.OFF` (the default)
|
| :param strength: Specify the comparison strength. This is also
| known as the ICU comparison level. This must be one of the following
| values:
|
| * :data:`~CollationStrength.PRIMARY`
| * :data:`~CollationStrength.SECONDARY`
| * :data:`~CollationStrength.TERTIARY` (the default)
| * :data:`~CollationStrength.QUATERNARY`
| * :data:`~CollationStrength.IDENTICAL`
|
| Each successive level builds upon the previous. For example, a
| `strength` of :data:`~CollationStrength.SECONDARY` differentiates
| characters based both on the unadorned base character and its accents.
|
| :param numericOrdering: If ``True``, order numbers numerically
| instead of in collation order (defaults to ``False``).
| :param alternate: Specify whether spaces and punctuation are
| considered base characters. This must be one of the following values:
|
| * :data:`~CollationAlternate.NON_IGNORABLE` (the default)
| * :data:`~CollationAlternate.SHIFTED`
|
| :param maxVariable: When `alternate` is
| :data:`~CollationAlternate.SHIFTED`, this option specifies what
| characters may be ignored. This must be one of the following values:
|
| * :data:`~CollationMaxVariable.PUNCT` (the default)
| * :data:`~CollationMaxVariable.SPACE`
|
| :param normalization: If ``True``, normalizes text into Unicode
| NFD. Defaults to ``False``.
| :param backwards: If ``True``, accents on characters are
| considered from the back of the word to the front, as it is done in some
| French dictionary ordering traditions. Defaults to ``False``.
| :param kwargs: Keyword arguments supplying any additional options
| to be sent with this Collation object.
|
| .. versionadded: 3.4
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, locale: 'str', caseLevel: 'Optional[bool]' = None, caseFirst: 'Optional[str]' = None, strength: 'Optional[int]' = None, numericOrdering: 'Optional[bool]' = None, alternate: 'Optional[str]' = None, maxVariable: 'Optional[str]' = None, normalization: 'Optional[bool]' = None, backwards: 'Optional[bool]' = None, **kwargs: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| document
| The document representation of this collation.
|
| .. note::
| :class:`Collation` is immutable. Mutating the value of
| :attr:`document` does not mutate this :class:`Collation`.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class CollationAlternate(builtins.object)
| An enum that defines values for `alternate` on a
| :class:`~pymongo.collation.Collation`.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| NON_IGNORABLE = 'non-ignorable'
|
| SHIFTED = 'shifted'
class CollationCaseFirst(builtins.object)
| An enum that defines values for `case_first` on a
| :class:`~pymongo.collation.Collation`.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| LOWER = 'lower'
|
| OFF = 'off'
|
| UPPER = 'upper'
class CollationMaxVariable(builtins.object)
| An enum that defines values for `max_variable` on a
| :class:`~pymongo.collation.Collation`.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| PUNCT = 'punct'
|
| SPACE = 'space'
class CollationStrength(builtins.object)
| An enum that defines values for `strength` on a
| :class:`~pymongo.collation.Collation`.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| IDENTICAL = 5
|
| PRIMARY = 1
|
| QUATERNARY = 4
|
| SECONDARY = 2
|
| TERTIARY = 3
FUNCTIONS
validate_collation_or_none(value: 'Optional[Union[Mapping[str, Any], Collation]]') -> 'Optional[dict[str, Any]]'
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\collation.py
pymongo.collection
Python Library Documentation: module pymongo.collection in pymongo
NAME
pymongo.collection - Collection level utilities for Mongo.
CLASSES
builtins.object
pymongo.synchronous.collection.ReturnDocument
pymongo.common.BaseObject(builtins.object)
pymongo.synchronous.collection.Collection(pymongo.common.BaseObject, typing.Generic)
typing.Generic(builtins.object)
pymongo.synchronous.collection.Collection(pymongo.common.BaseObject, typing.Generic)
class Collection(pymongo.common.BaseObject, typing.Generic)
| Collection(database: 'Database[_DocumentType]', name: 'str', create: 'Optional[bool]' = False, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None, session: 'Optional[ClientSession]' = None, **kwargs: 'Any') -> 'None'
|
| A Mongo collection.
|
| Method resolution order:
| Collection
| pymongo.common.BaseObject
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __bool__(self) -> 'NoReturn'
|
| __call__(self, *args: 'Any', **kwargs: 'Any') -> 'NoReturn'
| This is only here so that some API misusages are easier to debug.
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, name: 'str') -> 'Collection[_DocumentType]'
| Get a sub-collection of this collection by name.
|
| Raises InvalidName if an invalid collection name is used.
|
| :param name: the name of the collection to get
|
| __getitem__(self, name: 'str') -> 'Collection[_DocumentType]'
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, database: 'Database[_DocumentType]', name: 'str', create: 'Optional[bool]' = False, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None, session: 'Optional[ClientSession]' = None, **kwargs: 'Any') -> 'None'
| Get / create a Mongo collection.
|
| Raises :class:`TypeError` if `name` is not an instance of
| :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if `name` is
| not a valid collection name. Any additional keyword arguments will be used
| as options passed to the create command. See
| :meth:`~pymongo.database.Database.create_collection` for valid
| options.
|
| If `create` is ``True``, `collation` is specified, or any additional
| keyword arguments are present, a ``create`` command will be
| sent, using ``session`` if specified. Otherwise, a ``create`` command
| will not be sent and the collection will be created implicitly on first
| use. The optional ``session`` argument is *only* used for the ``create``
| command, it is not associated with the collection afterward.
|
| :param database: the database to get a collection from
| :param name: the name of the collection to get
| :param create: If ``True``, force collection
| creation even without options being set.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) database.codec_options is used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) database.read_preference is used.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) database.write_concern is used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) database.read_concern is used.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`. If a collation is provided,
| it will be passed to the create collection command.
| :param session: A
| :class:`~pymongo.client_session.ClientSession` that is used with
| the create collection command.
| :param kwargs: Additional keyword arguments will
| be passed as options for the create collection command.
|
| .. versionchanged:: 4.2
| Added the ``clusteredIndex`` and ``encryptedFields`` parameters.
|
| .. versionchanged:: 4.0
| Removed the reindex, map_reduce, inline_map_reduce,
| parallel_scan, initialize_unordered_bulk_op,
| initialize_ordered_bulk_op, group, count, insert, save,
| update, remove, find_and_modify, and ensure_index methods. See the
| :ref:`pymongo4-migration-guide`.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.4
| Support the `collation` option.
|
| .. versionchanged:: 3.2
| Added the read_concern option.
|
| .. versionchanged:: 3.0
| Added the codec_options, read_preference, and write_concern options.
| Removed the uuid_subtype attribute.
| :class:`~pymongo.collection.Collection` no longer returns an
| instance of :class:`~pymongo.collection.Collection` for attribute
| names with leading underscores. You must use dict-style lookups
| instead::
|
| collection['__my_collection__']
|
| Not:
|
| collection.__my_collection__
|
| .. seealso:: The MongoDB documentation on `collections <https://dochub.mongodb.org/core/collections>`_.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __next__(self) -> 'NoReturn'
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| aggregate(self, pipeline: '_Pipeline', session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'CommandCursor[_DocumentType]'
| Perform an aggregation using the aggregation framework on this
| collection.
|
| The :meth:`aggregate` method obeys the :attr:`read_preference` of this
| :class:`Collection`, except when ``$out`` or ``$merge`` are used on
| MongoDB <5.0, in which case
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY` is used.
|
| .. note:: This method does not support the 'explain' option. Please
| use `PyMongoExplain <https://pypi.org/project/pymongoexplain/>`_
| instead. An example is included in the `aggregation example <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/aggregation/#aggregation-example>`_
| documentation.
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with collection.aggregate() as cursor:
| for operation in cursor:
| print(operation)
|
| :param pipeline: a list of aggregation pipeline stages
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: A dict of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. ``"$$var"``). This option is
| only supported on MongoDB >= 5.0.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: extra `aggregate command`_ parameters.
|
| All optional `aggregate command`_ parameters should be passed as
| keyword arguments to this method. Valid options include, but are not
| limited to:
|
| - `allowDiskUse` (bool): Enables writing to temporary files. When set
| to True, aggregation stages can write data to the _tmp subdirectory
| of the --dbpath directory. The default is False.
| - `maxTimeMS` (int): The maximum amount of time to allow the operation
| to run in milliseconds.
| - `batchSize` (int): The maximum number of documents to return per
| batch. Ignored if the connected mongod or mongos does not support
| returning aggregate results using a cursor.
| - `collation` (optional): An instance of
| :class:`~pymongo.collation.Collation`.
| - `bypassDocumentValidation` (bool): If ``True``, allows the write to opt-out of document level validation.
|
|
| :return: A :class:`~pymongo.command_cursor.CommandCursor` over the result
| set.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
| Added ``let`` parameter.
| Support $merge and $out executing on secondaries according to the
| collection's :attr:`read_preference`.
| .. versionchanged:: 4.0
| Removed the ``useCursor`` option.
| .. versionchanged:: 3.9
| Apply this collection's read concern to pipelines containing the
| `$out` stage when connected to MongoDB >= 4.2.
| Added support for the ``$merge`` pipeline stage.
| Aggregations that write always use read preference
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
| .. versionchanged:: 3.6
| Added the `session` parameter. Added the `maxAwaitTimeMS` option.
| Deprecated the `useCursor` option.
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4. Support the `collation` option.
| .. versionchanged:: 3.0
| The :meth:`aggregate` method always returns a CommandCursor. The
| pipeline argument must be a list.
|
| .. seealso:: `Aggregation <https://mongodb.com/docs/manual/applications/aggregation/>`_
|
| .. _aggregate command:
| https://mongodb.com/docs/manual/reference/command/aggregate
|
| aggregate_raw_batches(self, pipeline: '_Pipeline', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'RawBatchCursor[_DocumentType]'
| Perform an aggregation and retrieve batches of raw BSON.
|
| Similar to the :meth:`aggregate` method but returns a
| :class:`~pymongo.cursor.RawBatchCursor`.
|
| This example demonstrates how to work with raw batches, but in practice
| raw batches should be passed to an external library that can decode
| BSON into another data type, rather than used with PyMongo's
| :mod:`bson` module.
|
| >>> import bson
| >>> cursor = db.test.aggregate_raw_batches([
| ... {'$project': {'x': {'$multiply': [2, '$x']}}}])
| >>> for batch in cursor:
| ... print(bson.decode_all(batch))
|
| .. note:: aggregate_raw_batches does not support auto encryption.
|
| .. versionchanged:: 3.12
| Added session support.
|
| .. versionadded:: 3.6
|
| bulk_write(self, requests: 'Sequence[_WriteOp[_DocumentType]]', ordered: 'bool' = True, bypass_document_validation: 'Optional[bool]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, let: 'Optional[Mapping[str, Any]]' = None) -> 'BulkWriteResult'
| Send a batch of write operations to the server.
|
| Requests are passed as a list of write operation instances (
| :class:`~pymongo.operations.InsertOne`,
| :class:`~pymongo.operations.UpdateOne`,
| :class:`~pymongo.operations.UpdateMany`,
| :class:`~pymongo.operations.ReplaceOne`,
| :class:`~pymongo.operations.DeleteOne`, or
| :class:`~pymongo.operations.DeleteMany`).
|
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
| ...
| >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
| >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}),
| ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)]
| >>> result = db.test.bulk_write(requests)
| >>> result.inserted_count
| 1
| >>> result.deleted_count
| 1
| >>> result.modified_count
| 0
| >>> result.upserted_ids
| {2: ObjectId('54f62ee28891e756a6e1abd5')}
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
| {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
| {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}
|
| :param requests: A list of write operations (see examples above).
| :param ordered: If ``True`` (the default) requests will be
| performed on the server serially, in the order provided. If an error
| occurs all remaining operations are aborted. If ``False`` requests
| will be performed on the server in arbitrary order, possibly in
| parallel, and all operations will be attempted.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
|
| :return: An instance of :class:`~pymongo.results.BulkWriteResult`.
|
| .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_
|
| .. note:: `bypass_document_validation` requires server version
| **>= 3.2**
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
| Added ``let`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.2
| Added bypass_document_validation support
|
| .. versionadded:: 3.0
|
| count_documents(self, filter: 'Mapping[str, Any]', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'int'
| Count the number of documents in this collection.
|
| .. note:: For a fast count of the total documents in a collection see
| :meth:`estimated_document_count`.
|
| The :meth:`count_documents` method is supported in a transaction.
|
| All optional parameters should be passed as keyword arguments
| to this method. Valid options include:
|
| - `skip` (int): The number of matching documents to skip before
| returning results.
| - `limit` (int): The maximum number of documents to count. Must be
| a positive integer. If not provided, no limit is imposed.
| - `maxTimeMS` (int): The maximum amount of time to allow this
| operation to run, in milliseconds.
| - `collation` (optional): An instance of
| :class:`~pymongo.collation.Collation`.
| - `hint` (string or list of tuples): The index to use. Specify either
| the index name as a string or the index specification as a list of
| tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]).
|
| The :meth:`count_documents` method obeys the :attr:`read_preference` of
| this :class:`Collection`.
|
| .. note:: When migrating from :meth:`count` to :meth:`count_documents`
| the following query operators must be replaced:
|
| +-------------+-------------------------------------+
| | Operator | Replacement |
| +=============+=====================================+
| | $where | `$expr`_ |
| +-------------+-------------------------------------+
| | $near | `$geoWithin`_ with `$center`_ |
| +-------------+-------------------------------------+
| | $nearSphere | `$geoWithin`_ with `$centerSphere`_ |
| +-------------+-------------------------------------+
|
| :param filter: A query document that selects which documents
| to count in the collection. Can be an empty document to count all
| documents.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: See list of options above.
|
|
| .. versionadded:: 3.7
|
| .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/
| .. _$geoWithin: https://mongodb.com/docs/manual/reference/operator/query/geoWithin/
| .. _$center: https://mongodb.com/docs/manual/reference/operator/query/center/
| .. _$centerSphere: https://mongodb.com/docs/manual/reference/operator/query/centerSphere/
|
| create_index(self, keys: '_IndexKeyHint', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'str'
| Creates an index on this collection.
|
| Takes either a single key or a list containing (key, direction) pairs
| or keys. If no direction is given, :data:`~pymongo.ASCENDING` will
| be assumed.
| The key(s) must be an instance of :class:`str` and the direction(s) must
| be one of (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
| :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOSPHERE`,
| :data:`~pymongo.HASHED`, :data:`~pymongo.TEXT`).
|
| To create a single key ascending index on the key ``'mike'`` we just
| use a string argument::
|
| >>> my_collection.create_index("mike")
|
| For a compound index on ``'mike'`` descending and ``'eliot'``
| ascending we need to use a list of tuples::
|
| >>> my_collection.create_index([("mike", pymongo.DESCENDING),
| ... "eliot"])
|
| All optional index creation parameters should be passed as
| keyword arguments to this method. For example::
|
| >>> my_collection.create_index([("mike", pymongo.DESCENDING)],
| ... background=True)
|
| Valid options include, but are not limited to:
|
| - `name`: custom name to use for this index - if none is
| given, a name will be generated.
| - `unique`: if ``True``, creates a uniqueness constraint on the
| index.
| - `background`: if ``True``, this index should be created in the
| background.
| - `sparse`: if ``True``, omit from the index any documents that lack
| the indexed field.
| - `bucketSize`: for use with geoHaystack indexes.
| Number of documents to group together within a certain proximity
| to a given longitude and latitude.
| - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
| collection. MongoDB will automatically delete documents from
| this collection after <int> seconds. The indexed field must
| be a UTC datetime or the data will not expire.
| - `partialFilterExpression`: A document that specifies a filter for
| a partial index.
| - `collation` (optional): An instance of
| :class:`~pymongo.collation.Collation`.
| - `wildcardProjection`: Allows users to include or exclude specific
| field paths from a `wildcard index`_ using the {"$**" : 1} key
| pattern. Requires MongoDB >= 4.2.
| - `hidden`: if ``True``, this index will be hidden from the query
| planner and will not be evaluated as part of query plan
| selection. Requires MongoDB >= 4.4.
|
| See the MongoDB documentation for a full list of supported options by
| server version.
|
| .. warning:: `dropDups` is not supported by MongoDB 3.0 or newer. The
| option is silently ignored by the server and unique index builds
| using the option will fail if a duplicate value is detected.
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
| :param keys: a single key or a list of (key, direction)
| pairs specifying the index to create
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: any additional index creation
| options (see the above list) should be passed as keyword
| arguments.
|
| .. versionchanged:: 4.4
| Allow passing a list containing (key, direction) pairs
| or keys for the ``keys`` parameter.
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added the ``hidden`` option.
| .. versionchanged:: 3.6
| Added ``session`` parameter. Added support for passing maxTimeMS
| in kwargs.
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4. Support the `collation` option.
| .. versionchanged:: 3.2
| Added partialFilterExpression to support partial indexes.
| .. versionchanged:: 3.0
| Renamed `key_or_list` to `keys`. Removed the `cache_for` option.
| :meth:`create_index` no longer caches index names. Removed support
| for the drop_dups and bucket_size aliases.
|
| .. seealso:: The MongoDB documentation on `indexes <https://dochub.mongodb.org/core/indexes>`_.
|
| .. _wildcard index: https://dochub.mongodb.org/core/index-wildcard/
|
| create_indexes(self, indexes: 'Sequence[IndexModel]', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'list[str]'
| Create one or more indexes on this collection.
|
| >>> from pymongo import IndexModel, ASCENDING, DESCENDING
| >>> index1 = IndexModel([("hello", DESCENDING),
| ... ("world", ASCENDING)], name="hello_world")
| >>> index2 = IndexModel([("goodbye", DESCENDING)])
| >>> db.test.create_indexes([index1, index2])
| ["hello_world", "goodbye_-1"]
|
| :param indexes: A list of :class:`~pymongo.operations.IndexModel`
| instances.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the createIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
|
|
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter. Added support for arbitrary keyword
| arguments.
|
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
| .. versionadded:: 3.0
|
| .. _createIndexes: https://mongodb.com/docs/manual/reference/command/createIndexes/
|
| create_search_index(self, model: 'Union[Mapping[str, Any], SearchIndexModel]', session: 'Optional[ClientSession]' = None, comment: 'Any' = None, **kwargs: 'Any') -> 'str'
| Create a single search index for the current collection.
|
| :param model: The model for the new search index.
| It can be given as a :class:`~pymongo.operations.SearchIndexModel`
| instance or a dictionary with a model "definition" and optional
| "name".
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the createSearchIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
| :return: The name of the new search index.
|
| .. note:: requires a MongoDB server version 7.0+ Atlas cluster.
|
| .. versionadded:: 4.5
|
| create_search_indexes(self, models: 'list[SearchIndexModel]', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'list[str]'
| Create multiple search indexes for the current collection.
|
| :param models: A list of :class:`~pymongo.operations.SearchIndexModel` instances.
| :param session: a :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the createSearchIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
| :return: A list of the newly created search index names.
|
| .. note:: requires a MongoDB server version 7.0+ Atlas cluster.
|
| .. versionadded:: 4.5
|
| delete_many(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None) -> 'DeleteResult'
| Delete one or more documents matching the filter.
|
| >>> db.test.count_documents({'x': 1})
| 3
| >>> result = db.test.delete_many({'x': 1})
| >>> result.deleted_count
| 3
| >>> db.test.count_documents({'x': 1})
| 0
|
| :param filter: A query that matches the documents to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: - An instance of :class:`~pymongo.results.DeleteResult`.
|
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
| .. versionchanged:: 3.4
| Added the `collation` option.
| .. versionadded:: 3.0
|
| delete_one(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None) -> 'DeleteResult'
| Delete a single document matching the filter.
|
| >>> db.test.count_documents({'x': 1})
| 3
| >>> result = db.test.delete_one({'x': 1})
| >>> result.deleted_count
| 1
| >>> db.test.count_documents({'x': 1})
| 2
|
| :param filter: A query that matches the document to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: - An instance of :class:`~pymongo.results.DeleteResult`.
|
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
| .. versionchanged:: 3.4
| Added the `collation` option.
| .. versionadded:: 3.0
|
| distinct(self, key: 'str', filter: 'Optional[Mapping[str, Any]]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, hint: 'Optional[_IndexKeyHint]' = None, **kwargs: 'Any') -> 'list[Any]'
| Get a list of distinct values for `key` among all documents
| in this collection.
|
| Raises :class:`TypeError` if `key` is not an instance of
| :class:`str`.
|
| All optional distinct parameters should be passed as keyword arguments
| to this method. Valid options include:
|
| - `maxTimeMS` (int): The maximum amount of time to allow the count
| command to run, in milliseconds.
| - `collation` (optional): An instance of
| :class:`~pymongo.collation.Collation`.
|
| The :meth:`distinct` method obeys the :attr:`read_preference` of
| this :class:`Collection`.
|
| :param key: name of the field for which we want to get the distinct
| values
| :param filter: A query document that specifies the documents
| from which to retrieve the distinct values.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to :meth:`~pymongo.collection.Collection.create_index`
| (e.g. ``[('field', ASCENDING)]``).
| :param kwargs: See list of options above.
|
| .. versionchanged:: 4.12
| Added ``hint`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.4
| Support the `collation` option.
|
| drop(self, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, encrypted_fields: 'Optional[Mapping[str, Any]]' = None) -> 'None'
| Alias for :meth:`~pymongo.database.Database.drop_collection`.
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param encrypted_fields: **(BETA)** Document that describes the encrypted fields for
| Queryable Encryption.
|
| The following two calls are equivalent:
|
| >>> db.foo.drop()
| >>> db.drop_collection("foo")
|
| .. versionchanged:: 4.2
| Added ``encrypted_fields`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.7
| :meth:`drop` now respects this :class:`Collection`'s :attr:`write_concern`.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| drop_index(self, index_or_name: '_IndexKeyHint', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'None'
| Drops the specified index on this collection.
|
| Can be used on non-existent collections or collections with no
| indexes. Raises OperationFailure on an error (e.g. trying to
| drop an index that does not exist). `index_or_name`
| can be either an index name (as returned by `create_index`),
| or an index specifier (as passed to `create_index`). An index
| specifier should be a list of (key, direction) pairs. Raises
| TypeError if index is not an instance of (str, unicode, list).
|
| .. warning::
|
| if a custom name was used on index creation (by
| passing the `name` parameter to :meth:`create_index`) the index
| **must** be dropped by name.
|
| :param index_or_name: index (or name of index) to drop
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the createIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
|
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
|
| .. versionchanged:: 3.6
| Added ``session`` parameter. Added support for arbitrary keyword
| arguments.
|
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| drop_indexes(self, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'None'
| Drops all indexes on this collection.
|
| Can be used on non-existent collections or collections with no indexes.
| Raises OperationFailure on an error.
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the createIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter. Added support for arbitrary keyword
| arguments.
|
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| drop_search_index(self, name: 'str', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'None'
| Delete a search index by index name.
|
| :param name: The name of the search index to be deleted.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the dropSearchIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
| .. note:: requires a MongoDB server version 7.0+ Atlas cluster.
|
| .. versionadded:: 4.5
|
| estimated_document_count(self, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'int'
| Get an estimate of the number of documents in this collection using
| collection metadata.
|
| The :meth:`estimated_document_count` method is **not** supported in a
| transaction.
|
| All optional parameters should be passed as keyword arguments
| to this method. Valid options include:
|
| - `maxTimeMS` (int): The maximum amount of time to allow this
| operation to run, in milliseconds.
|
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: See list of options above.
|
| .. versionchanged:: 4.2
| This method now always uses the `count`_ command. Due to an oversight in versions
| 5.0.0-5.0.8 of MongoDB, the count command was not included in V1 of the
| `versioned API <https://www.mongodb.com/docs/manual/reference/stable-api/#what-is-the-stable-api--and-should-you-use-it->`_. Users of the Stable API with estimated_document_count are
| recommended to upgrade their server version to 5.0.9+ or set
| :attr:`pymongo.server_api.ServerApi.strict` to ``False`` to avoid encountering errors.
|
| .. versionadded:: 3.7
| .. _count: https://mongodb.com/docs/manual/reference/command/count/
|
| find(self, *args: 'Any', **kwargs: 'Any') -> 'Cursor[_DocumentType]'
| Query the database.
|
| The `filter` argument is a query document that all results
| must match. For example:
|
| >>> db.test.find({"hello": "world"})
|
| only matches documents that have a key "hello" with value
| "world". Matches can have other keys *in addition* to
| "hello". The `projection` argument is used to specify a subset
| of fields that should be included in the result documents. By
| limiting results to a certain subset of fields you can cut
| down on network traffic and decoding time.
|
| Raises :class:`TypeError` if any of the arguments are of
| improper type. Returns an instance of
| :class:`~pymongo.cursor.Cursor` corresponding to this query.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with collection.find() as cursor:
| for doc in cursor:
| print(doc)
|
| The :meth:`find` method obeys the :attr:`read_preference` of
| this :class:`Collection`.
|
| :param filter: A query document that selects which documents
| to include in the result set. Can be an empty document to include
| all documents.
| :param projection: a list of field names that should be
| returned in the result set or a dict specifying the fields
| to include or exclude. If `projection` is a list "_id" will
| always be returned. Use a dict to exclude fields from
| the result (e.g. projection={'_id': False}).
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param skip: the number of documents to omit (from
| the start of the result set) when returning the results
| :param limit: the maximum number of results to
| return. A limit of 0 (the default) is equivalent to setting no
| limit.
| :param no_cursor_timeout: if False (the default), any
| returned cursor is closed by the server after 10 minutes of
| inactivity. If set to True, the returned cursor will never
| time out on the server. Care should be taken to ensure that
| cursors with no_cursor_timeout turned on are properly closed.
| :param cursor_type: the type of cursor to return. The valid
| options are defined by :class:`~pymongo.cursor.CursorType`:
|
| - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
| this find call will return a standard cursor over the result set.
| - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
| find call will be a tailable cursor - tailable cursors are only
| for use with capped collections. They are not closed when the
| last data is retrieved but are kept open and the cursor location
| marks the final document position. If more data is received
| iteration of the cursor will continue from the last document
| received. For details, see the `tailable cursor documentation
| <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_.
| - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
| of this find call will be a tailable cursor with the await flag
| set. The server will wait for a few seconds after returning the
| full result set so that it can capture and return additional data
| added during the query.
| - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
| find call will be an exhaust cursor. MongoDB will stream batched
| results to the client without waiting for the client to request
| each batch, reducing latency. See notes on compatibility below.
|
| :param sort: a list of (key, direction) pairs
| specifying the sort order for this query. See
| :meth:`~pymongo.cursor.Cursor.sort` for details.
| :param allow_partial_results: if True, mongos will return
| partial results if some shards are down instead of returning an
| error.
| :param oplog_replay: **DEPRECATED** - if True, set the
| oplogReplay query flag. Default: False.
| :param batch_size: Limits the number of documents returned in
| a single batch.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param return_key: If True, return only the index keys in
| each document.
| :param show_record_id: If True, adds a field ``$recordId`` in
| each document with the storage engine's internal record identifier.
| :param snapshot: **DEPRECATED** - If True, prevents the
| cursor from returning a document more than once because of an
| intervening write operation.
| :param hint: An index, in the same format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). Pass this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.hint` on the cursor to tell Mongo the
| proper index to use for the query.
| :param max_time_ms: Specifies a time limit for a query
| operation. If the specified time is exceeded, the operation will be
| aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. Pass
| this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.max_time_ms` on the cursor.
| :param max_scan: **DEPRECATED** - The maximum number of
| documents to scan. Pass this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.max_scan` on the cursor.
| :param min: A list of field, limit pairs specifying the
| inclusive lower bound for all keys of a specific index in order.
| Pass this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.min` on the cursor. ``hint`` must
| also be passed to ensure the query utilizes the correct index.
| :param max: A list of field, limit pairs specifying the
| exclusive upper bound for all keys of a specific index in order.
| Pass this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.max` on the cursor. ``hint`` must
| also be passed to ensure the query utilizes the correct index.
| :param comment: A string to attach to the query to help
| interpret and trace the operation in the server logs and in profile
| data. Pass this as an alternative to calling
| :meth:`~pymongo.cursor.Cursor.comment` on the cursor.
| :param allow_disk_use: if True, MongoDB may use temporary
| disk files to store data exceeding the system memory limit while
| processing a blocking sort operation. The option has no effect if
| MongoDB can satisfy the specified sort using an index, or if the
| blocking sort requires less memory than the 100 MiB limit. This
| option is only supported on MongoDB 4.4 and above.
|
| .. note:: There are a number of caveats to using
| :attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type:
|
| - The `limit` option can not be used with an exhaust cursor.
|
| - Exhaust cursors are not supported by mongos and can not be
| used with a sharded cluster.
|
| - A :class:`~pymongo.cursor.Cursor` instance created with the
| :attr:`~pymongo.cursor.CursorType.EXHAUST` cursor_type requires an
| exclusive :class:`~socket.socket` connection to MongoDB. If the
| :class:`~pymongo.cursor.Cursor` is discarded without being
| completely iterated the underlying :class:`~socket.socket`
| connection will be closed and discarded without being returned to
| the connection pool.
|
| .. versionchanged:: 4.0
| Removed the ``modifiers`` option.
| Empty projections (eg {} or []) are passed to the server as-is,
| rather than the previous behavior which substituted in a
| projection of ``{"_id": 1}``. This means that an empty projection
| will now return the entire document, not just the ``"_id"`` field.
|
| .. versionchanged:: 3.11
| Added the ``allow_disk_use`` option.
| Deprecated the ``oplog_replay`` option. Support for this option is
| deprecated in MongoDB 4.4. The query engine now automatically
| optimizes queries against the oplog without requiring this
| option to be set.
|
| .. versionchanged:: 3.7
| Deprecated the ``snapshot`` option, which is deprecated in MongoDB
| 3.6 and removed in MongoDB 4.0.
| Deprecated the ``max_scan`` option. Support for this option is
| deprecated in MongoDB 4.0. Use ``max_time_ms`` instead to limit
| server-side execution time.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.5
| Added the options ``return_key``, ``show_record_id``, ``snapshot``,
| ``hint``, ``max_time_ms``, ``max_scan``, ``min``, ``max``, and
| ``comment``.
| Deprecated the ``modifiers`` option.
|
| .. versionchanged:: 3.4
| Added support for the ``collation`` option.
|
| .. versionchanged:: 3.0
| Changed the parameter names ``spec``, ``fields``, ``timeout``, and
| ``partial`` to ``filter``, ``projection``, ``no_cursor_timeout``,
| and ``allow_partial_results`` respectively.
| Added the ``cursor_type``, ``oplog_replay``, and ``modifiers``
| options.
| Removed the ``network_timeout``, ``read_preference``, ``tag_sets``,
| ``secondary_acceptable_latency_ms``, ``max_scan``, ``snapshot``,
| ``tailable``, ``await_data``, ``exhaust``, ``as_class``, and
| slave_okay parameters.
| Removed ``compile_re`` option: PyMongo now always
| represents BSON regular expressions as :class:`~bson.regex.Regex`
| objects. Use :meth:`~bson.regex.Regex.try_compile` to attempt to
| convert from a BSON regular expression to a Python regular
| expression object.
| Soft deprecated the ``manipulate`` option.
|
| .. seealso:: The MongoDB documentation on `find <https://dochub.mongodb.org/core/find>`_.
|
| find_one(self, filter: 'Optional[Any]' = None, *args: 'Any', **kwargs: 'Any') -> 'Optional[_DocumentType]'
| Get a single document from the database.
|
| All arguments to :meth:`find` are also valid arguments for
| :meth:`find_one`, although any `limit` argument will be
| ignored. Returns a single document, or ``None`` if no matching
| document is found.
|
| The :meth:`find_one` method obeys the :attr:`read_preference` of
| this :class:`Collection`.
|
| :param filter: a dictionary specifying
| the query to be performed OR any other type to be used as
| the value for a query for ``"_id"``.
|
| :param args: any additional positional arguments
| are the same as the arguments to :meth:`find`.
|
| :param kwargs: any additional keyword arguments
| are the same as the arguments to :meth:`find`.
|
| :: code-block: python
|
| >>> collection.find_one(max_time_ms=100)
|
| find_one_and_delete(self, filter: 'Mapping[str, Any]', projection: 'Optional[Union[Mapping[str, Any], Iterable[str]]]' = None, sort: 'Optional[_IndexList]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'Optional[_DocumentType]'
| Finds a single document and deletes it, returning the document.
|
| >>> db.test.count_documents({'x': 1})
| 2
| >>> db.test.find_one_and_delete({'x': 1})
| {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
| >>> db.test.count_documents({'x': 1})
| 1
|
| Returns ``None`` if no document matches the filter.
|
| >>> db.test.find_one_and_delete({'_exists': False})
|
| If multiple documents match *filter*, a *sort* can be applied.
|
| >>> for doc in db.test.find({'x': 1}):
| ... print(doc)
| ...
| {'x': 1, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
| >>> db.test.find_one_and_delete(
| ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)])
| {'x': 1, '_id': 2}
|
| The *projection* option can be used to limit the fields returned.
|
| >>> db.test.find_one_and_delete({'x': 1}, projection={'_id': False})
| {'x': 1}
|
| :param filter: A query that matches the document to delete.
| :param projection: a list of field names that should be
| returned in the result document or a mapping specifying the fields
| to include or exclude. If `projection` is a list "_id" will
| always be returned. Use a mapping to exclude fields from
| the result (e.g. projection={'_id': False}).
| :param sort: a list of (key, direction) pairs
| specifying the sort order for the query. If multiple documents
| match the query, they are sorted and the first is deleted.
| :param hint: An index to use to support the query predicate
| specified either by its string name, or in the same format as
| passed to :meth:`~pymongo.collection.Collection.create_index`
| (e.g. ``[('field', ASCENDING)]``). This option is only supported
| on MongoDB 4.4 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: additional command arguments can be passed
| as keyword arguments (for example maxTimeMS can be used with
| recent server versions).
|
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
| .. versionchanged:: 3.2
| Respects write concern.
|
| .. warning:: Starting in PyMongo 3.2, this command uses the
| :class:`~pymongo.write_concern.WriteConcern` of this
| :class:`~pymongo.collection.Collection` when connected to MongoDB >=
| 3.2. Note that using an elevated write concern with this command may
| be slower compared to using the default write concern.
|
| .. versionchanged:: 3.4
| Added the `collation` option.
| .. versionadded:: 3.0
|
| find_one_and_replace(self, filter: 'Mapping[str, Any]', replacement: 'Mapping[str, Any]', projection: 'Optional[Union[Mapping[str, Any], Iterable[str]]]' = None, sort: 'Optional[_IndexList]' = None, upsert: 'bool' = False, return_document: 'bool' = False, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'Optional[_DocumentType]'
| Finds a single document and replaces it, returning either the
| original or the replaced document.
|
| >>> db.test.find_one({'x': 1})
| {'_id': 0, 'x': 1}
| >>> db.test.find_one_and_replace({'x': 1}, {'y': 2})
| {'_id': 0, 'x': 1}
| >>> db.test.find_one({'x': 1})
| >>> db.test.find_one({'y': 2})
| {'_id': 0, 'y': 2}
|
| Returns ``None`` if no document matches the filter.
|
| >>> db.test.find_one_and_replace({'_exists': False}, {'x': 1})
|
| The :meth:`find_one_and_replace` method differs from
| :meth:`find_one_and_update` by replacing the document matched by
| *filter*, rather than modifying the existing document.
|
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
| >>> db.test.find_one_and_replace({'x': 1}, {'y': 1})
| {'x': 1, '_id': 0}
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'y': 1, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
|
| :param filter: A query that matches the document to replace.
| :param replacement: The replacement document.
| :param projection: A list of field names that should be
| returned in the result document or a mapping specifying the fields
| to include or exclude. If `projection` is a list "_id" will
| always be returned. Use a mapping to exclude fields from
| the result (e.g. projection={'_id': False}).
| :param sort: a list of (key, direction) pairs
| specifying the sort order for the query. If multiple documents
| match the query, they are sorted and the first is replaced.
| :param upsert: When ``True``, inserts a new document if no
| document matches the query. Defaults to ``False``.
| :param return_document: If
| :attr:`ReturnDocument.BEFORE` (the default),
| returns the original document before it was replaced, or ``None``
| if no document matches. If
| :attr:`ReturnDocument.AFTER`, returns the replaced
| or inserted document.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: additional command arguments can be passed
| as keyword arguments (for example maxTimeMS can be used with
| recent server versions).
|
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
| .. versionchanged:: 3.4
| Added the ``collation`` option.
| .. versionchanged:: 3.2
| Respects write concern.
|
| .. warning:: Starting in PyMongo 3.2, this command uses the
| :class:`~pymongo.write_concern.WriteConcern` of this
| :class:`~pymongo.collection.Collection` when connected to MongoDB >=
| 3.2. Note that using an elevated write concern with this command may
| be slower compared to using the default write concern.
|
| .. versionadded:: 3.0
|
| find_one_and_update(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', projection: 'Optional[Union[Mapping[str, Any], Iterable[str]]]' = None, sort: 'Optional[_IndexList]' = None, upsert: 'bool' = False, return_document: 'bool' = False, array_filters: 'Optional[Sequence[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'Optional[_DocumentType]'
| Finds a single document and updates it, returning either the
| original or the updated document.
|
| >>> db.test.find_one({'_id': 665})
| {'_id': 665, 'done': False, 'count': 25}
| >>> db.test.find_one_and_update(
| ... {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}})
| {'_id': 665, 'done': False, 'count': 25}
| >>> db.test.find_one({'_id': 665})
| {'_id': 665, 'done': True, 'count': 26}
|
| Returns ``None`` if no document matches the filter.
|
| >>> db.test.find_one_and_update(
| ... {'_exists': False}, {'$inc': {'count': 1}})
|
| When the filter matches, by default :meth:`find_one_and_update`
| returns the original version of the document before the update was
| applied. To return the updated (or inserted in the case of
| *upsert*) version of the document instead, use the *return_document*
| option.
|
| >>> from pymongo import ReturnDocument
| >>> db.example.find_one_and_update(
| ... {'_id': 'userid'},
| ... {'$inc': {'seq': 1}},
| ... return_document=ReturnDocument.AFTER)
| {'_id': 'userid', 'seq': 1}
|
| You can limit the fields returned with the *projection* option.
|
| >>> db.example.find_one_and_update(
| ... {'_id': 'userid'},
| ... {'$inc': {'seq': 1}},
| ... projection={'seq': True, '_id': False},
| ... return_document=ReturnDocument.AFTER)
| {'seq': 2}
|
| The *upsert* option can be used to create the document if it doesn't
| already exist.
|
| >>> (db.example.delete_many({})).deleted_count
| 1
| >>> db.example.find_one_and_update(
| ... {'_id': 'userid'},
| ... {'$inc': {'seq': 1}},
| ... projection={'seq': True, '_id': False},
| ... upsert=True,
| ... return_document=ReturnDocument.AFTER)
| {'seq': 1}
|
| If multiple documents match *filter*, a *sort* can be applied.
|
| >>> for doc in db.test.find({'done': True}):
| ... print(doc)
| ...
| {'_id': 665, 'done': True, 'result': {'count': 26}}
| {'_id': 701, 'done': True, 'result': {'count': 17}}
| >>> db.test.find_one_and_update(
| ... {'done': True},
| ... {'$set': {'final': True}},
| ... sort=[('_id', pymongo.DESCENDING)])
| {'_id': 701, 'done': True, 'result': {'count': 17}}
|
| :param filter: A query that matches the document to update.
| :param update: The update operations to apply.
| :param projection: A list of field names that should be
| returned in the result document or a mapping specifying the fields
| to include or exclude. If `projection` is a list "_id" will
| always be returned. Use a dict to exclude fields from
| the result (e.g. projection={'_id': False}).
| :param sort: a list of (key, direction) pairs
| specifying the sort order for the query. If multiple documents
| match the query, they are sorted and the first is updated.
| :param upsert: When ``True``, inserts a new document if no
| document matches the query. Defaults to ``False``.
| :param return_document: If
| :attr:`ReturnDocument.BEFORE` (the default),
| returns the original document before it was updated. If
| :attr:`ReturnDocument.AFTER`, returns the updated
| or inserted document.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: additional command arguments can be passed
| as keyword arguments (for example maxTimeMS can be used with
| recent server versions).
|
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the ``update``.
| .. versionchanged:: 3.6
| Added the ``array_filters`` and ``session`` options.
| .. versionchanged:: 3.4
| Added the ``collation`` option.
| .. versionchanged:: 3.2
| Respects write concern.
|
| .. warning:: Starting in PyMongo 3.2, this command uses the
| :class:`~pymongo.write_concern.WriteConcern` of this
| :class:`~pymongo.collection.Collection` when connected to MongoDB >=
| 3.2. Note that using an elevated write concern with this command may
| be slower compared to using the default write concern.
|
| .. versionadded:: 3.0
|
| find_raw_batches(self, *args: 'Any', **kwargs: 'Any') -> 'RawBatchCursor[_DocumentType]'
| Query the database and retrieve batches of raw BSON.
|
| Similar to the :meth:`find` method but returns a
| :class:`~pymongo.cursor.RawBatchCursor`.
|
| This example demonstrates how to work with raw batches, but in practice
| raw batches should be passed to an external library that can decode
| BSON into another data type, rather than used with PyMongo's
| :mod:`bson` module.
|
| >>> import bson
| >>> cursor = db.test.find_raw_batches()
| >>> for batch in cursor:
| ... print(bson.decode_all(batch))
|
| .. note:: find_raw_batches does not support auto encryption.
|
| .. versionchanged:: 3.12
| Instead of ignoring the user-specified read concern, this method
| now sends it to the server when connected to MongoDB 3.6+.
|
| Added session support.
|
| .. versionadded:: 3.6
|
| index_information(self, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'MutableMapping[str, Any]'
| Get information on this collection's indexes.
|
| Returns a dictionary where the keys are index names (as
| returned by create_index()) and the values are dictionaries
| containing information about each index. The dictionary is
| guaranteed to contain at least a single key, ``"key"`` which
| is a list of (key, direction) pairs specifying the index (as
| passed to create_index()). It will also contain any other
| metadata about the indexes, except for the ``"ns"`` and
| ``"name"`` keys, which are cleaned. Example output might look
| like this:
|
| >>> db.test.create_index("x", unique=True)
| 'x_1'
| >>> db.test.index_information()
| {'_id_': {'key': [('_id', 1)]},
| 'x_1': {'unique': True, 'key': [('x', 1)]}}
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| insert_many(self, documents: 'Iterable[Union[_DocumentType, RawBSONDocument]]', ordered: 'bool' = True, bypass_document_validation: 'Optional[bool]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'InsertManyResult'
| Insert an iterable of documents.
|
| >>> db.test.count_documents({})
| 0
| >>> result = db.test.insert_many([{'x': i} for i in range(2)])
| >>> result.inserted_ids
| [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')]
| >>> db.test.count_documents({})
| 2
|
| :param documents: A iterable of documents to insert.
| :param ordered: If ``True`` (the default) documents will be
| inserted on the server serially, in the order provided. If an error
| occurs all remaining inserts are aborted. If ``False``, documents
| will be inserted on the server in arbitrary order, possibly in
| parallel, and all document inserts will be attempted.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: An instance of :class:`~pymongo.results.InsertManyResult`.
|
| .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_
|
| .. note:: `bypass_document_validation` requires server version
| **>= 3.2**
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.2
| Added bypass_document_validation support
|
| .. versionadded:: 3.0
|
| insert_one(self, document: 'Union[_DocumentType, RawBSONDocument]', bypass_document_validation: 'Optional[bool]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'InsertOneResult'
| Insert a single document.
|
| >>> db.test.count_documents({'x': 1})
| 0
| >>> result = db.test.insert_one({'x': 1})
| >>> result.inserted_id
| ObjectId('54f112defba522406c9cc208')
| >>> db.test.find_one({'x': 1})
| {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')}
|
| :param document: The document to insert. Must be a mutable mapping
| type. If the document does not have an _id field one will be
| added automatically.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: - An instance of :class:`~pymongo.results.InsertOneResult`.
|
| .. seealso:: `Writes and ids <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/insert/#overview>`_
|
| .. note:: `bypass_document_validation` requires server version
| **>= 3.2**
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.2
| Added bypass_document_validation support
|
| .. versionadded:: 3.0
|
| list_indexes(self, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'CommandCursor[MutableMapping[str, Any]]'
| Get a cursor over the index documents for this collection.
|
| >>> for index in db.test.list_indexes():
| ... print(index)
| ...
| SON([('v', 2), ('key', SON([('_id', 1)])), ('name', '_id_')])
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with collection.list_indexes() as cursor:
| for index in cursor:
| print(index)
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionadded:: 3.0
|
| list_search_indexes(self, name: 'Optional[str]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'CommandCursor[Mapping[str, Any]]'
| Return a cursor over search indexes for the current collection.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with collection.list_search_indexes() as cursor:
| for index in cursor:
| print(index)
|
| :param name: If given, the name of the index to search
| for. Only indexes with matching index names will be returned.
| If not given, all search indexes for the current collection
| will be returned.
| :param session: a :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: A :class:`~pymongo.command_cursor.CommandCursor` over the result
| set.
|
| .. note:: requires a MongoDB server version 7.0+ Atlas cluster.
|
| .. versionadded:: 4.5
|
| next = __next__(self) -> 'NoReturn'
|
| options(self, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None) -> 'MutableMapping[str, Any]'
| Get the options set on this collection.
|
| Returns a dictionary of options and their values - see
| :meth:`~pymongo.database.Database.create_collection` for more
| information on the possible options. Returns an empty
| dictionary if the collection has not been created yet.
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| rename(self, new_name: 'str', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'MutableMapping[str, Any]'
| Rename this collection.
|
| If operating in auth mode, client must be authorized as an
| admin to perform this operation. Raises :class:`TypeError` if
| `new_name` is not an instance of :class:`str`.
| Raises :class:`~pymongo.errors.InvalidName`
| if `new_name` is not a valid collection name.
|
| :param new_name: new name for this collection
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: additional arguments to the rename command
| may be passed as keyword arguments to this helper method
| (i.e. ``dropTarget=True``)
|
| .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
| this collection is automatically applied to this operation.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.4
| Apply this collection's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| replace_one(self, filter: 'Mapping[str, Any]', replacement: 'Mapping[str, Any]', upsert: 'bool' = False, bypass_document_validation: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, sort: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None) -> 'UpdateResult'
| Replace a single document matching the filter.
|
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')}
| >>> result = db.test.replace_one({'x': 1}, {'y': 1})
| >>> result.matched_count
| 1
| >>> result.modified_count
| 1
| >>> for doc in db.test.find({}):
| ... print(doc)
| ...
| {'y': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')}
|
| The *upsert* option can be used to insert a new document if a matching
| document does not exist.
|
| >>> result = db.test.replace_one({'x': 1}, {'x': 1}, True)
| >>> result.matched_count
| 0
| >>> result.modified_count
| 0
| >>> result.upserted_id
| ObjectId('54f11e5c8891e756a6e1abd4')
| >>> db.test.find_one({'x': 1})
| {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')}
|
| :param filter: A query that matches the document to replace.
| :param replacement: The new document.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
| This option is only supported on MongoDB 8.0 and above.
| :return: - An instance of :class:`~pymongo.results.UpdateResult`.
|
| .. versionchanged:: 4.11
| Added ``sort`` parameter.
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
| .. versionchanged:: 3.4
| Added the `collation` option.
| .. versionchanged:: 3.2
| Added bypass_document_validation support.
|
| .. versionadded:: 3.0
|
| update_many(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'bool' = False, array_filters: 'Optional[Sequence[Mapping[str, Any]]]' = None, bypass_document_validation: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None) -> 'UpdateResult'
| Update one or more documents that match the filter.
|
| >>> for doc in db.test.find():
| ... print(doc)
| ...
| {'x': 1, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
| >>> result = db.test.update_many({'x': 1}, {'$inc': {'x': 3}})
| >>> result.matched_count
| 3
| >>> result.modified_count
| 3
| >>> for doc in db.test.find():
| ... print(doc)
| ...
| {'x': 4, '_id': 0}
| {'x': 4, '_id': 1}
| {'x': 4, '_id': 2}
|
| :param filter: A query that matches the documents to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param bypass_document_validation: If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: - An instance of :class:`~pymongo.results.UpdateResult`.
|
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the `update`.
| .. versionchanged:: 3.6
| Added ``array_filters`` and ``session`` parameters.
| .. versionchanged:: 3.4
| Added the `collation` option.
| .. versionchanged:: 3.2
| Added bypass_document_validation support.
|
| .. versionadded:: 3.0
|
| update_one(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'bool' = False, bypass_document_validation: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[Sequence[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, session: 'Optional[ClientSession]' = None, let: 'Optional[Mapping[str, Any]]' = None, sort: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None) -> 'UpdateResult'
| Update a single document matching the filter.
|
| >>> for doc in db.test.find():
| ... print(doc)
| ...
| {'x': 1, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
| >>> result = db.test.update_one({'x': 1}, {'$inc': {'x': 3}})
| >>> result.matched_count
| 1
| >>> result.modified_count
| 1
| >>> for doc in db.test.find():
| ... print(doc)
| ...
| {'x': 4, '_id': 0}
| {'x': 1, '_id': 1}
| {'x': 1, '_id': 2}
|
| If ``upsert=True`` and no documents match the filter, create a
| new document based on the filter criteria and update modifications.
|
| >>> result = db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True)
| >>> result.matched_count
| 0
| >>> result.modified_count
| 0
| >>> result.upserted_id
| ObjectId('626a678eeaa80587d4bb3fb7')
| >>> db.test.find_one(result.upserted_id)
| {'_id': ObjectId('626a678eeaa80587d4bb3fb7'), 'x': -7}
|
| :param filter: A query that matches the document to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param bypass_document_validation: (optional) If ``True``, allows the
| write to opt-out of document level validation. Default is
| ``False``.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param let: Map of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. "$$var").
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
| This option is only supported on MongoDB 8.0 and above.
| :param comment: A user-provided comment to attach to this
| command.
|
| :return: - An instance of :class:`~pymongo.results.UpdateResult`.
|
| .. versionchanged:: 4.11
| Added ``sort`` parameter.
| .. versionchanged:: 4.1
| Added ``let`` parameter.
| Added ``comment`` parameter.
| .. versionchanged:: 3.11
| Added ``hint`` parameter.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the ``update``.
| .. versionchanged:: 3.6
| Added the ``array_filters`` and ``session`` parameters.
| .. versionchanged:: 3.4
| Added the ``collation`` option.
| .. versionchanged:: 3.2
| Added ``bypass_document_validation`` support.
|
| .. versionadded:: 3.0
|
| update_search_index(self, name: 'str', definition: 'Mapping[str, Any]', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'None'
| Update a search index by replacing the existing index definition with the provided definition.
|
| :param name: The name of the search index to be updated.
| :param definition: The new search index definition.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: optional arguments to the updateSearchIndexes
| command (like maxTimeMS) can be passed as keyword arguments.
|
| .. note:: requires a MongoDB server version 7.0+ Atlas cluster.
|
| .. versionadded:: 4.5
|
| watch(self, pipeline: 'Optional[_Pipeline]' = None, full_document: 'Optional[str]' = None, resume_after: 'Optional[Mapping[str, Any]]' = None, max_await_time_ms: 'Optional[int]' = None, batch_size: 'Optional[int]' = None, collation: 'Optional[_CollationIn]' = None, start_at_operation_time: 'Optional[Timestamp]' = None, session: 'Optional[ClientSession]' = None, start_after: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'CollectionChangeStream[_DocumentType]'
| Watch changes on this collection.
|
| Performs an aggregation with an implicit initial ``$changeStream``
| stage and returns a
| :class:`~pymongo.change_stream.CollectionChangeStream` cursor which
| iterates over changes on this collection.
|
| .. code-block:: python
|
| with db.collection.watch() as stream:
| for change in stream:
| print(change)
|
| The :class:`~pymongo.change_stream.CollectionChangeStream` iterable
| blocks until the next change document is returned or an error is
| raised. If the
| :meth:`~pymongo.change_stream.CollectionChangeStream.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 db.coll.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`_.
|
| .. note:: Using this helper method is preferred to directly calling
| :meth:`~pymongo.collection.Collection.aggregate` with a
| ``$changeStream`` stage, for the purpose of supporting
| resumability.
|
| .. warning:: This Collection's :attr:`read_concern` must be
| ``ReadConcern("majority")`` in order to use the ``$changeStream``
| stage.
|
| :param pipeline: 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.
| :param full_document: The fullDocument to pass as an option
| to the ``$changeStream`` stage. Allowed values: 'updateLookup',
| 'whenAvailable', 'required'. 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.
| :param full_document_before_change: Allowed values: 'whenAvailable'
| and 'required'. Change events may now result in a
| 'fullDocumentBeforeChange' response field.
| :param resume_after: 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.
| :param max_await_time_ms: The maximum time in milliseconds
| for the server to wait for changes before responding to a getMore
| operation.
| :param batch_size: The maximum number of documents to return
| per batch.
| :param collation: The :class:`~pymongo.collation.Collation`
| to use for the aggregation.
| :param start_at_operation_time: 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.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param start_after: The same as `resume_after` except that
| `start_after` can resume notifications after an invalidate event.
| This option and `resume_after` are mutually exclusive.
| :param comment: A user-provided comment to attach to this
| command.
| :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
| :return: A :class:`~pymongo.change_stream.CollectionChangeStream` cursor.
|
| .. versionchanged:: 4.3
| Added `show_expanded_events` parameter.
|
| .. versionchanged:: 4.2
| Added ``full_document_before_change`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.9
| Added the ``start_after`` parameter.
|
| .. versionchanged:: 3.7
| Added the ``start_at_operation_time`` parameter.
|
| .. versionadded:: 3.6
|
| .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.
|
| .. _change streams specification:
| https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
|
| with_options(self, codec_options: 'Optional[bson.CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'Collection[_DocumentType] | Collection[_DocumentTypeArg]'
| Get a clone of this collection changing the specified settings.
|
| >>> coll1.read_preference
| Primary()
| >>> from pymongo import ReadPreference
| >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY)
| >>> coll1.read_preference
| Primary()
| >>> coll2.read_preference
| Secondary(tag_sets=None)
|
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`Collection`
| is used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
| for options.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`Collection`
| is used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`Collection`
| is used.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| database
| The :class:`~pymongo.database.Database` that this
| :class:`Collection` is a part of.
|
| full_name
| The full name of this :class:`Collection`.
|
| The full name is of the form `database_name.collection_name`.
|
| name
| The name of this :class:`Collection`.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __iter__ = None
|
| __orig_bases__ = (<class 'pymongo.common.BaseObject'>, typing.Generic[...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.common.BaseObject:
|
| codec_options
| Read only access to the :class:`~bson.codec_options.CodecOptions`
| of this instance.
|
| read_concern
| Read only access to the :class:`~pymongo.read_concern.ReadConcern`
| of this instance.
|
| .. versionadded:: 3.2
|
| read_preference
| Read only access to the read preference of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`read_preference` attribute is now read only.
|
| write_concern
| Read only access to the :class:`~pymongo.write_concern.WriteConcern`
| of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`write_concern` attribute is now read only.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.common.BaseObject:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ReturnDocument(builtins.object)
| An enum used with
| :meth:`~pymongo.collection.Collection.find_one_and_replace` and
| :meth:`~pymongo.collection.Collection.find_one_and_update`.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| AFTER = True
|
| BEFORE = False
DATA
__all__ = ['Collection', 'ReturnDocument']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\collection.py
pymongo.command_cursor
Python Library Documentation: module pymongo.command_cursor in pymongo
NAME
pymongo.command_cursor - CommandCursor class to iterate over command results.
CLASSES
pymongo.synchronous.cursor_base._CursorBase(pymongo.cursor_shared._AgnosticCursorBase)
pymongo.synchronous.command_cursor.CommandCursor
pymongo.synchronous.command_cursor.RawBatchCommandCursor
class CommandCursor(pymongo.synchronous.cursor_base._CursorBase)
| CommandCursor(collection: 'Collection[_DocumentType]', cursor_info: 'Mapping[str, Any]', address: 'Optional[_Address]', batch_size: 'int' = 0, max_await_time_ms: 'Optional[int]' = None, session: 'Optional[ClientSession]' = None, comment: 'Any' = None) -> 'None'
|
| A cursor / iterator over command cursors.
|
| Method resolution order:
| CommandCursor
| pymongo.synchronous.cursor_base._CursorBase
| pymongo.cursor_shared._AgnosticCursorBase
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'CommandCursor[_DocumentType]'
|
| __init__(self, collection: 'Collection[_DocumentType]', cursor_info: 'Mapping[str, Any]', address: 'Optional[_Address]', batch_size: 'int' = 0, max_await_time_ms: 'Optional[int]' = None, session: 'Optional[ClientSession]' = None, comment: 'Any' = None) -> 'None'
| Create a new command cursor.
|
| __iter__(self) -> 'Iterator[_DocumentType]'
|
| __next__(self) -> '_DocumentType'
|
| batch_size(self, batch_size: 'int') -> 'CommandCursor[_DocumentType]'
| Limits the number of documents returned in one batch. Each batch
| requires a round trip to the server. It can be adjusted to optimize
| performance and limit data transfer.
|
| .. note:: batch_size can not override MongoDB's internal limits on the
| amount of data it will return to the client in a single batch (i.e
| if you set batch size to 1,000,000,000, MongoDB will currently only
| return 4-16MB of results per batch).
|
| Raises :exc:`TypeError` if `batch_size` is not an integer.
| Raises :exc:`ValueError` if `batch_size` is less than ``0``.
|
| :param batch_size: The size of each batch of results requested.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next document without waiting
| indefinitely for data.
|
| If no document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there is no additional data) then ``None`` is returned.
|
| :return: The next document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 4.5
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (pymongo.synchronous.cursor_base._CursorBase[~_Docume...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| close(self) -> 'None'
| Explicitly close / kill this cursor.
|
| to_list(self, length: 'Optional[int]' = None) -> 'list[_DocumentType]'
| Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``.
|
| To use::
|
| >>> cursor.to_list()
|
| Or, to read at most n items from the cursor::
|
| >>> cursor.to_list(n)
|
| If the cursor is empty or has no more results, an empty list will be returned.
|
| .. versionadded:: 4.9
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| session
| The cursor's :class:`~pymongo.client_session.ClientSession`, or None.
|
| .. versionadded:: 3.6
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __del__(self) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| address
| The (host, port) of the server used, or None.
|
| .. versionchanged:: 3.0
| Renamed from "conn_id".
|
| alive
| Does this cursor have the potential to return more data?
|
| This is mostly useful with `tailable cursors
| <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_
| since they will stop iterating even though they *may* return more
| results in the future.
|
| With regular cursors, simply use an asynchronous for loop instead of :attr:`alive`::
|
| async for doc in collection.find():
| print(doc)
|
| .. note:: Even if :attr:`alive` is True, :meth:`next` can raise
| :exc:`StopIteration`. :attr:`alive` can also be True while iterating
| a cursor from a failed server. In this case :attr:`alive` will
| return False after :meth:`next` fails to retrieve the next batch
| of results from the server.
|
| cursor_id
| Returns the id of the cursor.
|
| .. versionadded:: 2.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class RawBatchCommandCursor(CommandCursor)
| RawBatchCommandCursor(collection: 'Collection[_DocumentType]', cursor_info: 'Mapping[str, Any]', address: 'Optional[_Address]', batch_size: 'int' = 0, max_await_time_ms: 'Optional[int]' = None, session: 'Optional[ClientSession]' = None, comment: 'Any' = None) -> 'None'
|
| Method resolution order:
| RawBatchCommandCursor
| CommandCursor
| pymongo.synchronous.cursor_base._CursorBase
| pymongo.cursor_shared._AgnosticCursorBase
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __getitem__(self, index: 'int') -> 'NoReturn'
|
| __init__(self, collection: 'Collection[_DocumentType]', cursor_info: 'Mapping[str, Any]', address: 'Optional[_Address]', batch_size: 'int' = 0, max_await_time_ms: 'Optional[int]' = None, session: 'Optional[ClientSession]' = None, comment: 'Any' = None) -> 'None'
| Create a new cursor / iterator over raw batches of BSON data.
|
| Should not be called directly by application developers -
| see :meth:`~pymongo.collection.Collection.aggregate_raw_batches`
| instead.
|
| .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (pymongo.synchronous.command_cursor.CommandCursor[~_D...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from CommandCursor:
|
| __enter__(self) -> 'CommandCursor[_DocumentType]'
|
| __iter__(self) -> 'Iterator[_DocumentType]'
|
| __next__(self) -> '_DocumentType'
|
| batch_size(self, batch_size: 'int') -> 'CommandCursor[_DocumentType]'
| Limits the number of documents returned in one batch. Each batch
| requires a round trip to the server. It can be adjusted to optimize
| performance and limit data transfer.
|
| .. note:: batch_size can not override MongoDB's internal limits on the
| amount of data it will return to the client in a single batch (i.e
| if you set batch size to 1,000,000,000, MongoDB will currently only
| return 4-16MB of results per batch).
|
| Raises :exc:`TypeError` if `batch_size` is not an integer.
| Raises :exc:`ValueError` if `batch_size` is less than ``0``.
|
| :param batch_size: The size of each batch of results requested.
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| try_next(self) -> 'Optional[_DocumentType]'
| Advance the cursor without blocking indefinitely.
|
| This method returns the next document without waiting
| indefinitely for data.
|
| If no document is cached locally then this method runs a single
| getMore command. If the getMore yields any documents, the next
| document is returned, otherwise, if the getMore returns no documents
| (because there is no additional data) then ``None`` is returned.
|
| :return: The next document or ``None`` when no document is available
| after running a single getMore or when the cursor is closed.
|
| .. versionadded:: 4.5
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| close(self) -> 'None'
| Explicitly close / kill this cursor.
|
| to_list(self, length: 'Optional[int]' = None) -> 'list[_DocumentType]'
| Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``.
|
| To use::
|
| >>> cursor.to_list()
|
| Or, to read at most n items from the cursor::
|
| >>> cursor.to_list(n)
|
| If the cursor is empty or has no more results, an empty list will be returned.
|
| .. versionadded:: 4.9
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| session
| The cursor's :class:`~pymongo.client_session.ClientSession`, or None.
|
| .. versionadded:: 3.6
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __del__(self) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| address
| The (host, port) of the server used, or None.
|
| .. versionchanged:: 3.0
| Renamed from "conn_id".
|
| alive
| Does this cursor have the potential to return more data?
|
| This is mostly useful with `tailable cursors
| <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_
| since they will stop iterating even though they *may* return more
| results in the future.
|
| With regular cursors, simply use an asynchronous for loop instead of :attr:`alive`::
|
| async for doc in collection.find():
| print(doc)
|
| .. note:: Even if :attr:`alive` is True, :meth:`next` can raise
| :exc:`StopIteration`. :attr:`alive` can also be True while iterating
| a cursor from a failed server. In this case :attr:`alive` will
| return False after :meth:`next` fails to retrieve the next batch
| of results from the server.
|
| cursor_id
| Returns the id of the cursor.
|
| .. versionadded:: 2.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
__all__ = ['CommandCursor', 'RawBatchCommandCursor']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\command_cursor.py
pymongo.common
Python Library Documentation: module pymongo.common in pymongo
NAME
pymongo.common - Functions and classes common to multiple pymongo modules.
CLASSES
builtins.object
BaseObject
builtins.tuple(builtins.object)
Version
class BaseObject(builtins.object)
| BaseObject(codec_options: 'CodecOptions[Any]', read_preference: '_ServerMode', write_concern: 'WriteConcern', read_concern: 'ReadConcern') -> 'None'
|
| A base class that provides attributes and methods common
| to multiple pymongo classes.
|
| SHOULD NOT BE USED BY DEVELOPERS EXTERNAL TO MONGODB.
|
| Methods defined here:
|
| __init__(self, codec_options: 'CodecOptions[Any]', read_preference: '_ServerMode', write_concern: 'WriteConcern', read_concern: 'ReadConcern') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| codec_options
| Read only access to the :class:`~bson.codec_options.CodecOptions`
| of this instance.
|
| read_concern
| Read only access to the :class:`~pymongo.read_concern.ReadConcern`
| of this instance.
|
| .. versionadded:: 3.2
|
| read_preference
| Read only access to the read preference of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`read_preference` attribute is now read only.
|
| write_concern
| Read only access to the :class:`~pymongo.write_concern.WriteConcern`
| of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`write_concern` attribute is now read only.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
class Version(builtins.tuple)
| Version(*version: 'int') -> 'Version'
|
| A class that can be used to compare version strings.
|
| Method resolution order:
| Version
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __str__(self) -> 'str'
| Return str(self).
|
| at_least(self, *other_version: 'Any') -> 'bool'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_string(version_string: 'str') -> 'Version'
|
| from_version_array(version_array: 'Any') -> 'Version'
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *version: 'int') -> 'Version'
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __orig_bases__ = (tuple[int, ...],)
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...)
| See PEP 585
FUNCTIONS
check_for_min_version(package_name: 'str') -> 'tuple[str, str, bool]'
Test whether an installed package is of the desired version.
clean_node(node: 'str') -> 'tuple[str, int]'
Split and normalize a node name from a hello response.
get_validated_options(options: 'Mapping[str, Any]', warn: 'bool' = True) -> 'MutableMapping[str, Any]'
Validate each entry in options and raise a warning if it is not valid.
Returns a copy of options with invalid entries removed.
:param opts: A dict containing MongoDB URI options.
:param warn: If ``True`` then warnings will be logged and
invalid options will be ignored. Otherwise, invalid options will
cause errors.
has_c() -> 'bool'
Is the C extension installed?
partition_node(node: 'str') -> 'tuple[str, int]'
Split a host:port string into (host, int(port)) pair.
raise_config_error(key: 'str', suggestions: 'Optional[list[str]]' = None) -> 'NoReturn'
Raise ConfigurationError with the given key name.
validate(option: 'str', value: 'Any') -> 'tuple[str, Any]'
Generic validation function.
validate_appname_or_none(option: 'str', value: 'Any') -> 'Optional[str]'
Validate the appname option.
validate_auth_mechanism(option: 'str', value: 'Any') -> 'str'
Validate the authMechanism URI option.
validate_auth_mechanism_properties(option: 'str', value: 'Any') -> 'dict[str, Union[bool, str]]'
Validate authMechanismProperties.
validate_auto_encryption_opts_or_none(option: 'Any', value: 'Any') -> 'Optional[Any]'
Validate the driver keyword arg.
validate_boolean_or_string(option: 'str', value: 'Any') -> 'bool'
Validates that value is True, False, 'true', or 'false'.
validate_datetime_conversion(option: 'Any', value: 'Any') -> 'Optional[DatetimeConversion]'
Validate a DatetimeConversion string.
validate_document_class(option: 'str', value: 'Any') -> 'Union[Type[MutableMapping[str, Any]], Type[RawBSONDocument]]'
Validate the document_class option.
validate_driver_or_none(option: 'Any', value: 'Any') -> 'Optional[DriverInfo]'
Validate the driver keyword arg.
validate_integer(option: 'str', value: 'Any') -> 'int'
Validates that 'value' is an integer (or basestring representation).
validate_is_callable_or_none(option: 'Any', value: 'Any') -> 'Optional[Callable[..., Any]]'
Validates that 'value' is a callable.
validate_is_document_type(option: 'str', value: 'Any') -> 'None'
Validate the type of method arguments that expect a MongoDB document.
validate_is_mapping(option: 'str', value: 'Any') -> 'None'
Validate the type of method arguments that expect a document.
validate_list(option: 'str', value: 'Any') -> 'list[Any]'
Validates that 'value' is a list.
validate_list_or_mapping(option: 'Any', value: 'Any') -> 'None'
Validates that 'value' is a list or a document.
validate_list_or_none(option: 'Any', value: 'Any') -> 'Optional[list[Any]]'
Validates that 'value' is a list or None.
validate_max_staleness(option: 'str', value: 'Any') -> 'int'
Validates maxStalenessSeconds according to the Max Staleness Spec.
validate_non_negative_int_or_basestring(option: 'Any', value: 'Any') -> 'Union[int, str]'
Validates that 'value' is an integer or string.
validate_non_negative_integer(option: 'str', value: 'Any') -> 'int'
Validate that 'value' is a positive integer or 0.
validate_non_negative_integer_or_none(option: 'str', value: 'Any') -> 'Optional[int]'
Validate that 'value' is a positive integer or 0 or None.
validate_ok_for_replace(replacement: 'Mapping[str, Any]') -> 'None'
Validate a replacement document.
validate_ok_for_update(update: 'Any') -> 'None'
Validate an update document.
validate_positive_float(option: 'str', value: 'Any') -> 'float'
Validates that 'value' is a float, or can be converted to one, and is
positive.
validate_positive_float_or_zero(option: 'str', value: 'Any') -> 'float'
Validates that 'value' is 0 or a positive float, or can be converted to
0 or a positive float.
validate_positive_integer(option: 'str', value: 'Any') -> 'int'
Validate that 'value' is a positive integer, which does not include 0.
validate_read_preference(dummy: 'Any', value: 'Any') -> '_ServerMode'
Validate a read preference.
validate_read_preference_mode(dummy: 'Any', value: 'Any') -> '_ServerMode'
Validate read preference mode for a MongoClient.
.. versionchanged:: 3.5
Returns the original ``value`` instead of the validated read preference
mode.
validate_read_preference_tags(name: 'str', value: 'Any') -> 'list[dict[str, str]]'
Parse readPreferenceTags if passed as a client kwarg.
validate_readable(option: 'str', value: 'Any') -> 'Optional[str]'
Validates that 'value' is file-like and readable.
validate_server_api_or_none(option: 'Any', value: 'Any') -> 'Optional[ServerApi]'
Validate the server_api keyword arg.
validate_server_monitoring_mode(option: 'str', value: 'str') -> 'str'
Validate the serverMonitoringMode option.
validate_string(option: 'str', value: 'Any') -> 'str'
Validates that 'value' is an instance of `str`.
validate_string_or_none(option: 'str', value: 'Any') -> 'Optional[str]'
Validates that 'value' is an instance of `basestring` or `None`.
validate_timeout_or_none(option: 'str', value: 'Any') -> 'Optional[float]'
Validates a timeout specified in milliseconds returning
a value in floating point seconds.
validate_timeout_or_none_or_zero(option: 'Any', value: 'Any') -> 'Optional[float]'
Validates a timeout specified in milliseconds returning
a value in floating point seconds. value=0 and value="0" are treated the
same as value=None which means unlimited timeout.
validate_timeout_or_zero(option: 'str', value: 'Any') -> 'float'
Validates a timeout specified in milliseconds returning
a value in floating point seconds for the case where None is an error
and 0 is valid. Setting the timeout to nothing in the URI string is a
config error.
validate_timeoutms(option: 'Any', value: 'Any') -> 'Optional[float]'
Validates a timeout specified in milliseconds returning
a value in floating point seconds.
validate_type_registry(option: 'Any', value: 'Any') -> 'Optional[TypeRegistry]'
Validate the type_registry option.
validate_tzinfo(dummy: 'Any', value: 'Any') -> 'Optional[datetime.tzinfo]'
Validate the tzinfo option
validate_unicode_decode_error_handler(dummy: 'Any', value: 'str') -> 'str'
Validate the Unicode decode error handler option of CodecOptions.
validate_uuid_representation(dummy: 'Any', value: 'Any') -> 'int'
Validate the uuid representation option selected in the URI.
DATA
COMMAND_NOT_FOUND_CODES = (59,)
CONNECT_TIMEOUT = 20.0
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
DEFAULT_WRITE_CONCERN = WriteConcern()
ENABLE_OVERLOAD_RETARGETING = False
EVENTS_QUEUE_FREQUENCY = 1
HEARTBEAT_FREQUENCY = 10
INTERNAL_URI_OPTION_NAME_MAP = {'ssl': 'tls'}
Iterator = typing.Iterator
A generic version of collections.abc.Iterator.
KILL_CURSOR_FREQUENCY = 1
KW_VALIDATORS = {'authoidcallowedhosts': <function validate_list>, 'au...
LOCAL_THRESHOLD_MS = 15
MAX_ADAPTIVE_RETRIES = 2
MAX_BSON_SIZE = 16777216
MAX_CONNECTING = 2
MAX_IDLE_TIME_MS = None
MAX_IDLE_TIME_SEC = None
MAX_MESSAGE_SIZE = 48000000
MAX_POOL_SIZE = 100
MAX_SUPPORTED_WIRE_VERSION = 25
MAX_WIRE_VERSION = 0
MAX_WRITE_BATCH_SIZE = 100000
MIN_HEARTBEAT_INTERVAL = 0.5
MIN_POOL_SIZE = 0
MIN_SRV_RESCAN_INTERVAL = 60
MIN_SUPPORTED_SERVER_VERSION = '4.2'
MIN_SUPPORTED_WIRE_VERSION = 8
MIN_WIRE_VERSION = 0
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
NONSPEC_OPTIONS_VALIDATOR_MAP = {'connect': <function validate_boolean...
NoReturn = typing.NoReturn
Special type indicating functions that never return.
Example::
from typing import NoReturn
def stop() -> NoReturn:
raise Exception('no way')
NoReturn can also be used as a bottom type, a type that
has no values. Starting in Python 3.11, the Never type should
be used for this concept instead. Type checkers should treat the two
equivalently.
ORDERED_TYPES = (<class 'bson.son.SON'>, <class 'collections.OrderedDi...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
RETRY_READS = True
RETRY_WRITES = True
SERVER_MONITORING_MODE = 'auto'
SERVER_SELECTION_TIMEOUT = 30
SRV_SERVICE_NAME = 'mongodb'
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TIMEOUT_OPTIONS = ['connecttimeoutms', 'heartbeatfrequencyms', 'maxidl...
TYPE_CHECKING = False
Type = typing.Type
Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
UNAUTHORIZED_CODES = (13, 16547, 16548)
URI_OPTIONS_ALIAS_MAP = {'tls': ['ssl']}
URI_OPTIONS_DEPRECATION_MAP = {}
URI_OPTIONS_VALIDATOR_MAP = {'appname': <function validate_appname_or_...
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
VALIDATORS = {'appname': <function validate_appname_or_none>, 'authmec...
WAIT_QUEUE_TIMEOUT = None
WRITE_CONCERN_OPTIONS = frozenset({'fsync', 'j', 'journal', 'w', 'wtim...
__annotations__ = {'COMMAND_NOT_FOUND_CODES': 'Sequence[int]', 'INTERN...
alias = 'ssl'
aliases = ['ssl']
optname = 'tls'
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\common.py
pymongo.compression_support
Python Library Documentation: module pymongo.compression_support in pymongo
NAME
pymongo.compression_support
DESCRIPTION
# Copyright 2018 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
CLASSES
builtins.object
CompressionSettings
SnappyContext
ZlibContext
ZstdContext
class CompressionSettings(builtins.object)
| CompressionSettings(compressors: 'list[str]', zlib_compression_level: 'int')
|
| Methods defined here:
|
| __init__(self, compressors: 'list[str]', zlib_compression_level: 'int')
| Initialize self. See help(type(self)) for accurate signature.
|
| get_compression_context(self, compressors: 'Optional[list[str]]') -> 'Union[SnappyContext, ZlibContext, ZstdContext, None]'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class SnappyContext(builtins.object)
| Static methods defined here:
|
| compress(data: 'bytes') -> 'bytes'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| compressor_id = 1
class ZlibContext(builtins.object)
| ZlibContext(level: 'int')
|
| Methods defined here:
|
| __init__(self, level: 'int')
| Initialize self. See help(type(self)) for accurate signature.
|
| compress(self, data: 'bytes') -> 'bytes'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| compressor_id = 2
class ZstdContext(builtins.object)
| Static methods defined here:
|
| compress(data: 'bytes') -> 'bytes'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| compressor_id = 3
FUNCTIONS
decompress(data: 'bytes | memoryview', compressor_id: 'int') -> 'bytes'
validate_compressors(dummy: 'Any', value: 'Union[str, Iterable[str]]') -> 'list[str]'
validate_zlib_compression_level(option: 'str', value: 'Any') -> 'int'
DATA
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\compression_support.py
pymongo.cursor
Python Library Documentation: module pymongo.cursor in pymongo
NAME
pymongo.cursor - Cursor class to iterate over Mongo query results.
CLASSES
builtins.object
pymongo.cursor_shared.CursorType
pymongo.synchronous.cursor_base._CursorBase(pymongo.cursor_shared._AgnosticCursorBase)
pymongo.synchronous.cursor.Cursor
pymongo.synchronous.cursor.RawBatchCursor
class Cursor(pymongo.synchronous.cursor_base._CursorBase)
| Cursor(collection: 'Collection[_DocumentType]', filter: 'Optional[Mapping[str, Any]]' = None, projection: 'Optional[Union[Mapping[str, Any], Iterable[str]]]' = None, skip: 'int' = 0, limit: 'int' = 0, no_cursor_timeout: 'bool' = False, cursor_type: 'int' = 0, sort: 'Optional[_Sort]' = None, allow_partial_results: 'bool' = False, oplog_replay: 'bool' = False, batch_size: 'int' = 0, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_Hint]' = None, max_scan: 'Optional[int]' = None, max_time_ms: 'Optional[int]' = None, max: 'Optional[_Sort]' = None, min: 'Optional[_Sort]' = None, return_key: 'Optional[bool]' = None, show_record_id: 'Optional[bool]' = None, snapshot: 'Optional[bool]' = None, comment: 'Optional[Any]' = None, session: 'Optional[ClientSession]' = None, allow_disk_use: 'Optional[bool]' = None, let: 'Optional[bool]' = None) -> 'None'
|
| Method resolution order:
| Cursor
| pymongo.synchronous.cursor_base._CursorBase
| pymongo.cursor_shared._AgnosticCursorBase
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __copy__(self) -> 'Cursor[_DocumentType]'
| Support function for `copy.copy()`.
|
| .. versionadded:: 2.4
|
| __deepcopy__(self, memo: 'Any') -> 'Any'
| Support function for `copy.deepcopy()`.
|
| .. versionadded:: 2.4
|
| __enter__(self) -> 'Cursor[_DocumentType]'
|
| __getitem__(self, index: 'Union[int, slice]') -> 'Union[_DocumentType, Cursor[_DocumentType]]'
| Get a single document or a slice of documents from this cursor.
|
| .. warning:: A :class:`~Cursor` is not a Python :class:`list`. Each
| index access or slice requires that a new query be run using skip
| and limit. Do not iterate the cursor using index accesses.
| The following example is **extremely inefficient** and may return
| surprising results::
|
| cursor = db.collection.find()
| # Warning: This runs a new query for each document.
| # Don't do this!
| for idx in range(10):
| print(cursor[idx])
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this
| cursor has already been used.
|
| To get a single document use an integral index, e.g.::
|
| >>> db.test.find()[50]
|
| An :class:`IndexError` will be raised if the index is negative
| or greater than the amount of documents in this cursor. Any
| limit previously applied to this cursor will be ignored.
|
| To get a slice of documents use a slice index, e.g.::
|
| >>> db.test.find()[20:25]
|
| This will return this cursor with a limit of ``5`` and skip of
| ``20`` applied. Using a slice index will override any prior
| limits or skips applied to this cursor (including those
| applied through previous calls to this method). Raises
| :class:`IndexError` when the slice has a step, a negative
| start value, or a stop value less than or equal to the start
| value.
|
| :param index: An integer or slice index to be applied to this cursor
|
| __init__(self, collection: 'Collection[_DocumentType]', filter: 'Optional[Mapping[str, Any]]' = None, projection: 'Optional[Union[Mapping[str, Any], Iterable[str]]]' = None, skip: 'int' = 0, limit: 'int' = 0, no_cursor_timeout: 'bool' = False, cursor_type: 'int' = 0, sort: 'Optional[_Sort]' = None, allow_partial_results: 'bool' = False, oplog_replay: 'bool' = False, batch_size: 'int' = 0, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_Hint]' = None, max_scan: 'Optional[int]' = None, max_time_ms: 'Optional[int]' = None, max: 'Optional[_Sort]' = None, min: 'Optional[_Sort]' = None, return_key: 'Optional[bool]' = None, show_record_id: 'Optional[bool]' = None, snapshot: 'Optional[bool]' = None, comment: 'Optional[Any]' = None, session: 'Optional[ClientSession]' = None, allow_disk_use: 'Optional[bool]' = None, let: 'Optional[bool]' = None) -> 'None'
| Create a new cursor.
|
| Should not be called directly by application developers - see
| :meth:`~pymongo.collection.Collection.find` instead.
|
| .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
|
| __iter__(self) -> 'Cursor[_DocumentType]'
|
| __next__(self) -> '_DocumentType'
|
| add_option(self, mask: 'int') -> 'Cursor[_DocumentType]'
| Set arbitrary query flags using a bitmask.
|
| To set the tailable flag:
| cursor.add_option(2)
|
| allow_disk_use(self, allow_disk_use: 'bool') -> 'Cursor[_DocumentType]'
| Specifies whether MongoDB can use temporary disk files while
| processing a blocking sort operation.
|
| Raises :exc:`TypeError` if `allow_disk_use` is not a boolean.
|
| .. note:: `allow_disk_use` requires server version **>= 4.4**
|
| :param allow_disk_use: if True, MongoDB may use temporary
| disk files to store data exceeding the system memory limit while
| processing a blocking sort operation.
|
| .. versionadded:: 3.11
|
| batch_size(self, batch_size: 'int') -> 'Cursor[_DocumentType]'
| Limits the number of documents returned in one batch. Each batch
| requires a round trip to the server. It can be adjusted to optimize
| performance and limit data transfer.
|
| .. note:: batch_size can not override MongoDB's internal limits on the
| amount of data it will return to the client in a single batch (i.e
| if you set batch size to 1,000,000,000, MongoDB will currently only
| return 4-16MB of results per batch).
|
| Raises :exc:`TypeError` if `batch_size` is not an integer.
| Raises :exc:`ValueError` if `batch_size` is less than ``0``.
| Raises :exc:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used. The last `batch_size`
| applied to this cursor takes precedence.
|
| :param batch_size: The size of each batch of results requested.
|
| clone(self) -> 'Cursor[_DocumentType]'
| Get a clone of this cursor.
|
| Returns a new Cursor instance with options matching those that have
| been set on the current instance. The clone will be completely
| unevaluated, even if the current instance has been partially or
| completely evaluated.
|
| collation(self, collation: 'Optional[_CollationIn]') -> 'Cursor[_DocumentType]'
| Adds a :class:`~pymongo.collation.Collation` to this query.
|
| Raises :exc:`TypeError` if `collation` is not an instance of
| :class:`~pymongo.collation.Collation` or a ``dict``. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
| already been used. Only the last collation applied to this cursor has
| any effect.
|
| :param collation: An instance of :class:`~pymongo.collation.Collation`.
|
| comment(self, comment: 'Any') -> 'Cursor[_DocumentType]'
| Adds a 'comment' to the cursor.
|
| http://mongodb.com/docs/manual/reference/operator/comment/
|
| :param comment: A string to attach to the query to help interpret and
| trace the operation in the server logs and in profile data.
|
| .. versionadded:: 2.7
|
| distinct(self, key: 'str') -> 'list[Any]'
| Get a list of distinct values for `key` among all documents
| in the result set of this query.
|
| Raises :class:`TypeError` if `key` is not an instance of
| :class:`str`.
|
| The :meth:`distinct` method obeys the
| :attr:`~pymongo.collection.Collection.read_preference` of the
| :class:`~pymongo.collection.Collection` instance on which
| :meth:`~pymongo.collection.Collection.find` was called.
|
| :param key: name of key for which we want to get the distinct values
|
| .. seealso:: :meth:`pymongo.collection.Collection.distinct`
|
| explain(self) -> '_DocumentType'
| Returns an explain plan record for this cursor.
|
| .. note:: This method uses the default verbosity mode of the
| `explain command
| <https://mongodb.com/docs/manual/reference/command/explain/>`_,
| ``allPlansExecution``. To use a different verbosity use
| :meth:`~pymongo.database.Database.command` to run the explain
| command directly.
|
| .. note:: The timeout of this method can be set using :func:`pymongo.timeout`.
|
| .. seealso:: The MongoDB documentation on `explain <https://dochub.mongodb.org/core/explain>`_.
|
| hint(self, index: 'Optional[_Hint]') -> 'Cursor[_DocumentType]'
| Adds a 'hint', telling Mongo the proper index to use for the query.
|
| Judicious use of hints can greatly improve query
| performance. When doing a query on multiple fields (at least
| one of which is indexed) pass the indexed field as a hint to
| the query. Raises :class:`~pymongo.errors.OperationFailure` if the
| provided hint requires an index that does not exist on this collection,
| and raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
| already been used.
|
| `index` should be an index as passed to
| :meth:`~pymongo.collection.Collection.create_index`
| (e.g. ``[('field', ASCENDING)]``) or the name of the index.
| If `index` is ``None`` any existing hint for this query is
| cleared. The last hint applied to this cursor takes precedence
| over all others.
|
| :param index: index to hint on (as an index specifier)
|
| limit(self, limit: 'int') -> 'Cursor[_DocumentType]'
| Limits the number of results to be returned by this cursor.
|
| Raises :exc:`TypeError` if `limit` is not an integer. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
| has already been used. The last `limit` applied to this cursor
| takes precedence. A limit of ``0`` is equivalent to no limit.
|
| :param limit: the number of results to return
|
| .. seealso:: The MongoDB documentation on `limit <https://dochub.mongodb.org/core/limit>`_.
|
| max(self, spec: '_Sort') -> 'Cursor[_DocumentType]'
| Adds ``max`` operator that specifies upper bound for specific index.
|
| When using ``max``, :meth:`~hint` should also be configured to ensure
| the query uses the expected index and starting in MongoDB 4.2
| :meth:`~hint` will be required.
|
| :param spec: a list of field, limit pairs specifying the exclusive
| upper bound for all keys of a specific index in order.
|
| .. versionchanged:: 3.8
| Deprecated cursors that use ``max`` without a :meth:`~hint`.
|
| .. versionadded:: 2.7
|
| max_await_time_ms(self, max_await_time_ms: 'Optional[int]') -> 'Cursor[_DocumentType]'
| Specifies a time limit for a getMore operation on a
| :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
| types of cursor max_await_time_ms is ignored.
|
| Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or
| ``None``. Raises :exc:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used.
|
| .. note:: `max_await_time_ms` requires server version **>= 3.2**
|
| :param max_await_time_ms: the time limit after which the operation is
| aborted
|
| .. versionadded:: 3.2
|
| max_scan(self, max_scan: 'Optional[int]') -> 'Cursor[_DocumentType]'
| **DEPRECATED** - Limit the number of documents to scan when
| performing the query.
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this
| cursor has already been used. Only the last :meth:`max_scan`
| applied to this cursor has any effect.
|
| :param max_scan: the maximum number of documents to scan
|
| .. versionchanged:: 3.7
| Deprecated :meth:`max_scan`. Support for this option is deprecated in
| MongoDB 4.0. Use :meth:`max_time_ms` instead to limit server side
| execution time.
|
| max_time_ms(self, max_time_ms: 'Optional[int]') -> 'Cursor[_DocumentType]'
| Specifies a time limit for a query operation. If the specified
| time is exceeded, the operation will be aborted and
| :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
| is ``None`` no limit is applied.
|
| Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``.
| Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
| has already been used.
|
| :param max_time_ms: the time limit after which the operation is aborted
|
| min(self, spec: '_Sort') -> 'Cursor[_DocumentType]'
| Adds ``min`` operator that specifies lower bound for specific index.
|
| When using ``min``, :meth:`~hint` should also be configured to ensure
| the query uses the expected index and starting in MongoDB 4.2
| :meth:`~hint` will be required.
|
| :param spec: a list of field, limit pairs specifying the inclusive
| lower bound for all keys of a specific index in order.
|
| .. versionchanged:: 3.8
| Deprecated cursors that use ``min`` without a :meth:`~hint`.
|
| .. versionadded:: 2.7
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| remove_option(self, mask: 'int') -> 'Cursor[_DocumentType]'
| Unset arbitrary query flags using a bitmask.
|
| To unset the tailable flag:
| cursor.remove_option(2)
|
| rewind(self) -> 'Cursor[_DocumentType]'
| Rewind this cursor to its unevaluated state.
|
| Reset this cursor if it has been partially or completely evaluated.
| Any options that are present on the cursor will remain in effect.
| Future iterating performed on this cursor will cause new queries to
| be sent to the server, even if the resultant data has already been
| retrieved by this cursor.
|
| skip(self, skip: 'int') -> 'Cursor[_DocumentType]'
| Skips the first `skip` results of this cursor.
|
| Raises :exc:`TypeError` if `skip` is not an integer. Raises
| :exc:`ValueError` if `skip` is less than ``0``. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
| already been used. The last `skip` applied to this cursor takes
| precedence.
|
| :param skip: the number of results to skip
|
| sort(self, key_or_list: '_Hint', direction: 'Optional[Union[int, str]]' = None) -> 'Cursor[_DocumentType]'
| Sorts this cursor's results.
|
| Pass a field name and a direction, either
| :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`.::
|
| for doc in collection.find().sort('field', pymongo.ASCENDING):
| print(doc)
|
| To sort by multiple fields, pass a list of (key, direction) pairs.
| If just a name is given, :data:`~pymongo.ASCENDING` will be inferred::
|
| for doc in collection.find().sort([
| 'field1',
| ('field2', pymongo.DESCENDING)]):
| print(doc)
|
| Text search results can be sorted by relevance::
|
| cursor = db.test.find(
| {'$text': {'$search': 'some words'}},
| {'score': {'$meta': 'textScore'}})
|
| # Sort by 'score' field.
| cursor.sort([('score', {'$meta': 'textScore'})])
|
| for doc in cursor:
| print(doc)
|
| For more advanced text search functionality, see MongoDB's
| `Atlas Search <https://docs.atlas.mongodb.com/atlas-search/>`_.
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
| already been used. Only the last :meth:`sort` applied to this
| cursor has any effect.
|
| :param key_or_list: a single key or a list of (key, direction)
| pairs specifying the keys to sort on
| :param direction: only used if `key_or_list` is a single
| key, if not given :data:`~pymongo.ASCENDING` is assumed
|
| where(self, code: 'Union[str, Code]') -> 'Cursor[_DocumentType]'
| Adds a `$where`_ clause to this query.
|
| The `code` argument must be an instance of :class:`str` or
| :class:`~bson.code.Code` containing a JavaScript expression.
| This expression will be evaluated for each document scanned.
| Only those documents for which the expression evaluates to
| *true* will be returned as results. The keyword *this* refers
| to the object currently being scanned. For example::
|
| # Find all documents where field "a" is less than "b" plus "c".
| for doc in db.test.find().where('this.a < (this.b + this.c)'):
| print(doc)
|
| Raises :class:`TypeError` if `code` is not an instance of
| :class:`str`. Raises :class:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used. Only the last call to
| :meth:`where` applied to a :class:`Cursor` has any effect.
|
| .. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code`
| with scope variables. Consider using `$expr`_ instead.
|
| :param code: JavaScript expression to use as a filter
|
| .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/
| .. _$where: https://mongodb.com/docs/manual/reference/operator/query/where/
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| collection
| The :class:`~pymongo.collection.Collection` that this
| :class:`Cursor` is iterating.
|
| retrieved
| The number of documents retrieved so far.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (pymongo.synchronous.cursor_base._CursorBase[~_Docume...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| close(self) -> 'None'
| Explicitly close / kill this cursor.
|
| to_list(self, length: 'Optional[int]' = None) -> 'list[_DocumentType]'
| Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``.
|
| To use::
|
| >>> cursor.to_list()
|
| Or, to read at most n items from the cursor::
|
| >>> cursor.to_list(n)
|
| If the cursor is empty or has no more results, an empty list will be returned.
|
| .. versionadded:: 4.9
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| session
| The cursor's :class:`~pymongo.client_session.ClientSession`, or None.
|
| .. versionadded:: 3.6
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __del__(self) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| address
| The (host, port) of the server used, or None.
|
| .. versionchanged:: 3.0
| Renamed from "conn_id".
|
| alive
| Does this cursor have the potential to return more data?
|
| This is mostly useful with `tailable cursors
| <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_
| since they will stop iterating even though they *may* return more
| results in the future.
|
| With regular cursors, simply use an asynchronous for loop instead of :attr:`alive`::
|
| async for doc in collection.find():
| print(doc)
|
| .. note:: Even if :attr:`alive` is True, :meth:`next` can raise
| :exc:`StopIteration`. :attr:`alive` can also be True while iterating
| a cursor from a failed server. In this case :attr:`alive` will
| return False after :meth:`next` fails to retrieve the next batch
| of results from the server.
|
| cursor_id
| Returns the id of the cursor.
|
| .. versionadded:: 2.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class CursorType(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| EXHAUST = 64
|
| NON_TAILABLE = 0
|
| TAILABLE = 2
|
| TAILABLE_AWAIT = 34
class RawBatchCursor(Cursor)
| RawBatchCursor(collection: 'Collection[_DocumentType]', *args: 'Any', **kwargs: 'Any') -> 'None'
|
| A cursor / iterator over raw batches of BSON data from a query result.
|
| Method resolution order:
| RawBatchCursor
| Cursor
| pymongo.synchronous.cursor_base._CursorBase
| pymongo.cursor_shared._AgnosticCursorBase
| typing.Generic
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __getitem__(self, index: 'Any') -> 'NoReturn'
| Get a single document or a slice of documents from this cursor.
|
| .. warning:: A :class:`~Cursor` is not a Python :class:`list`. Each
| index access or slice requires that a new query be run using skip
| and limit. Do not iterate the cursor using index accesses.
| The following example is **extremely inefficient** and may return
| surprising results::
|
| cursor = db.collection.find()
| # Warning: This runs a new query for each document.
| # Don't do this!
| for idx in range(10):
| print(cursor[idx])
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this
| cursor has already been used.
|
| To get a single document use an integral index, e.g.::
|
| >>> db.test.find()[50]
|
| An :class:`IndexError` will be raised if the index is negative
| or greater than the amount of documents in this cursor. Any
| limit previously applied to this cursor will be ignored.
|
| To get a slice of documents use a slice index, e.g.::
|
| >>> db.test.find()[20:25]
|
| This will return this cursor with a limit of ``5`` and skip of
| ``20`` applied. Using a slice index will override any prior
| limits or skips applied to this cursor (including those
| applied through previous calls to this method). Raises
| :class:`IndexError` when the slice has a step, a negative
| start value, or a stop value less than or equal to the start
| value.
|
| :param index: An integer or slice index to be applied to this cursor
|
| __init__(self, collection: 'Collection[_DocumentType]', *args: 'Any', **kwargs: 'Any') -> 'None'
| Create a new cursor / iterator over raw batches of BSON data.
|
| Should not be called directly by application developers -
| see :meth:`~pymongo.collection.Collection.find_raw_batches`
| instead.
|
| .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
|
| explain(self) -> '_DocumentType'
| Returns an explain plan record for this cursor.
|
| .. seealso:: The MongoDB documentation on `explain <https://dochub.mongodb.org/core/explain>`_.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (pymongo.synchronous.cursor.Cursor[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Methods inherited from Cursor:
|
| __copy__(self) -> 'Cursor[_DocumentType]'
| Support function for `copy.copy()`.
|
| .. versionadded:: 2.4
|
| __deepcopy__(self, memo: 'Any') -> 'Any'
| Support function for `copy.deepcopy()`.
|
| .. versionadded:: 2.4
|
| __enter__(self) -> 'Cursor[_DocumentType]'
|
| __iter__(self) -> 'Cursor[_DocumentType]'
|
| __next__(self) -> '_DocumentType'
|
| add_option(self, mask: 'int') -> 'Cursor[_DocumentType]'
| Set arbitrary query flags using a bitmask.
|
| To set the tailable flag:
| cursor.add_option(2)
|
| allow_disk_use(self, allow_disk_use: 'bool') -> 'Cursor[_DocumentType]'
| Specifies whether MongoDB can use temporary disk files while
| processing a blocking sort operation.
|
| Raises :exc:`TypeError` if `allow_disk_use` is not a boolean.
|
| .. note:: `allow_disk_use` requires server version **>= 4.4**
|
| :param allow_disk_use: if True, MongoDB may use temporary
| disk files to store data exceeding the system memory limit while
| processing a blocking sort operation.
|
| .. versionadded:: 3.11
|
| batch_size(self, batch_size: 'int') -> 'Cursor[_DocumentType]'
| Limits the number of documents returned in one batch. Each batch
| requires a round trip to the server. It can be adjusted to optimize
| performance and limit data transfer.
|
| .. note:: batch_size can not override MongoDB's internal limits on the
| amount of data it will return to the client in a single batch (i.e
| if you set batch size to 1,000,000,000, MongoDB will currently only
| return 4-16MB of results per batch).
|
| Raises :exc:`TypeError` if `batch_size` is not an integer.
| Raises :exc:`ValueError` if `batch_size` is less than ``0``.
| Raises :exc:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used. The last `batch_size`
| applied to this cursor takes precedence.
|
| :param batch_size: The size of each batch of results requested.
|
| clone(self) -> 'Cursor[_DocumentType]'
| Get a clone of this cursor.
|
| Returns a new Cursor instance with options matching those that have
| been set on the current instance. The clone will be completely
| unevaluated, even if the current instance has been partially or
| completely evaluated.
|
| collation(self, collation: 'Optional[_CollationIn]') -> 'Cursor[_DocumentType]'
| Adds a :class:`~pymongo.collation.Collation` to this query.
|
| Raises :exc:`TypeError` if `collation` is not an instance of
| :class:`~pymongo.collation.Collation` or a ``dict``. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
| already been used. Only the last collation applied to this cursor has
| any effect.
|
| :param collation: An instance of :class:`~pymongo.collation.Collation`.
|
| comment(self, comment: 'Any') -> 'Cursor[_DocumentType]'
| Adds a 'comment' to the cursor.
|
| http://mongodb.com/docs/manual/reference/operator/comment/
|
| :param comment: A string to attach to the query to help interpret and
| trace the operation in the server logs and in profile data.
|
| .. versionadded:: 2.7
|
| distinct(self, key: 'str') -> 'list[Any]'
| Get a list of distinct values for `key` among all documents
| in the result set of this query.
|
| Raises :class:`TypeError` if `key` is not an instance of
| :class:`str`.
|
| The :meth:`distinct` method obeys the
| :attr:`~pymongo.collection.Collection.read_preference` of the
| :class:`~pymongo.collection.Collection` instance on which
| :meth:`~pymongo.collection.Collection.find` was called.
|
| :param key: name of key for which we want to get the distinct values
|
| .. seealso:: :meth:`pymongo.collection.Collection.distinct`
|
| hint(self, index: 'Optional[_Hint]') -> 'Cursor[_DocumentType]'
| Adds a 'hint', telling Mongo the proper index to use for the query.
|
| Judicious use of hints can greatly improve query
| performance. When doing a query on multiple fields (at least
| one of which is indexed) pass the indexed field as a hint to
| the query. Raises :class:`~pymongo.errors.OperationFailure` if the
| provided hint requires an index that does not exist on this collection,
| and raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
| already been used.
|
| `index` should be an index as passed to
| :meth:`~pymongo.collection.Collection.create_index`
| (e.g. ``[('field', ASCENDING)]``) or the name of the index.
| If `index` is ``None`` any existing hint for this query is
| cleared. The last hint applied to this cursor takes precedence
| over all others.
|
| :param index: index to hint on (as an index specifier)
|
| limit(self, limit: 'int') -> 'Cursor[_DocumentType]'
| Limits the number of results to be returned by this cursor.
|
| Raises :exc:`TypeError` if `limit` is not an integer. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
| has already been used. The last `limit` applied to this cursor
| takes precedence. A limit of ``0`` is equivalent to no limit.
|
| :param limit: the number of results to return
|
| .. seealso:: The MongoDB documentation on `limit <https://dochub.mongodb.org/core/limit>`_.
|
| max(self, spec: '_Sort') -> 'Cursor[_DocumentType]'
| Adds ``max`` operator that specifies upper bound for specific index.
|
| When using ``max``, :meth:`~hint` should also be configured to ensure
| the query uses the expected index and starting in MongoDB 4.2
| :meth:`~hint` will be required.
|
| :param spec: a list of field, limit pairs specifying the exclusive
| upper bound for all keys of a specific index in order.
|
| .. versionchanged:: 3.8
| Deprecated cursors that use ``max`` without a :meth:`~hint`.
|
| .. versionadded:: 2.7
|
| max_await_time_ms(self, max_await_time_ms: 'Optional[int]') -> 'Cursor[_DocumentType]'
| Specifies a time limit for a getMore operation on a
| :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
| types of cursor max_await_time_ms is ignored.
|
| Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or
| ``None``. Raises :exc:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used.
|
| .. note:: `max_await_time_ms` requires server version **>= 3.2**
|
| :param max_await_time_ms: the time limit after which the operation is
| aborted
|
| .. versionadded:: 3.2
|
| max_scan(self, max_scan: 'Optional[int]') -> 'Cursor[_DocumentType]'
| **DEPRECATED** - Limit the number of documents to scan when
| performing the query.
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this
| cursor has already been used. Only the last :meth:`max_scan`
| applied to this cursor has any effect.
|
| :param max_scan: the maximum number of documents to scan
|
| .. versionchanged:: 3.7
| Deprecated :meth:`max_scan`. Support for this option is deprecated in
| MongoDB 4.0. Use :meth:`max_time_ms` instead to limit server side
| execution time.
|
| max_time_ms(self, max_time_ms: 'Optional[int]') -> 'Cursor[_DocumentType]'
| Specifies a time limit for a query operation. If the specified
| time is exceeded, the operation will be aborted and
| :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
| is ``None`` no limit is applied.
|
| Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``.
| Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
| has already been used.
|
| :param max_time_ms: the time limit after which the operation is aborted
|
| min(self, spec: '_Sort') -> 'Cursor[_DocumentType]'
| Adds ``min`` operator that specifies lower bound for specific index.
|
| When using ``min``, :meth:`~hint` should also be configured to ensure
| the query uses the expected index and starting in MongoDB 4.2
| :meth:`~hint` will be required.
|
| :param spec: a list of field, limit pairs specifying the inclusive
| lower bound for all keys of a specific index in order.
|
| .. versionchanged:: 3.8
| Deprecated cursors that use ``min`` without a :meth:`~hint`.
|
| .. versionadded:: 2.7
|
| next(self) -> '_DocumentType'
| Advance the cursor.
|
| remove_option(self, mask: 'int') -> 'Cursor[_DocumentType]'
| Unset arbitrary query flags using a bitmask.
|
| To unset the tailable flag:
| cursor.remove_option(2)
|
| rewind(self) -> 'Cursor[_DocumentType]'
| Rewind this cursor to its unevaluated state.
|
| Reset this cursor if it has been partially or completely evaluated.
| Any options that are present on the cursor will remain in effect.
| Future iterating performed on this cursor will cause new queries to
| be sent to the server, even if the resultant data has already been
| retrieved by this cursor.
|
| skip(self, skip: 'int') -> 'Cursor[_DocumentType]'
| Skips the first `skip` results of this cursor.
|
| Raises :exc:`TypeError` if `skip` is not an integer. Raises
| :exc:`ValueError` if `skip` is less than ``0``. Raises
| :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
| already been used. The last `skip` applied to this cursor takes
| precedence.
|
| :param skip: the number of results to skip
|
| sort(self, key_or_list: '_Hint', direction: 'Optional[Union[int, str]]' = None) -> 'Cursor[_DocumentType]'
| Sorts this cursor's results.
|
| Pass a field name and a direction, either
| :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`.::
|
| for doc in collection.find().sort('field', pymongo.ASCENDING):
| print(doc)
|
| To sort by multiple fields, pass a list of (key, direction) pairs.
| If just a name is given, :data:`~pymongo.ASCENDING` will be inferred::
|
| for doc in collection.find().sort([
| 'field1',
| ('field2', pymongo.DESCENDING)]):
| print(doc)
|
| Text search results can be sorted by relevance::
|
| cursor = db.test.find(
| {'$text': {'$search': 'some words'}},
| {'score': {'$meta': 'textScore'}})
|
| # Sort by 'score' field.
| cursor.sort([('score', {'$meta': 'textScore'})])
|
| for doc in cursor:
| print(doc)
|
| For more advanced text search functionality, see MongoDB's
| `Atlas Search <https://docs.atlas.mongodb.com/atlas-search/>`_.
|
| Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
| already been used. Only the last :meth:`sort` applied to this
| cursor has any effect.
|
| :param key_or_list: a single key or a list of (key, direction)
| pairs specifying the keys to sort on
| :param direction: only used if `key_or_list` is a single
| key, if not given :data:`~pymongo.ASCENDING` is assumed
|
| where(self, code: 'Union[str, Code]') -> 'Cursor[_DocumentType]'
| Adds a `$where`_ clause to this query.
|
| The `code` argument must be an instance of :class:`str` or
| :class:`~bson.code.Code` containing a JavaScript expression.
| This expression will be evaluated for each document scanned.
| Only those documents for which the expression evaluates to
| *true* will be returned as results. The keyword *this* refers
| to the object currently being scanned. For example::
|
| # Find all documents where field "a" is less than "b" plus "c".
| for doc in db.test.find().where('this.a < (this.b + this.c)'):
| print(doc)
|
| Raises :class:`TypeError` if `code` is not an instance of
| :class:`str`. Raises :class:`~pymongo.errors.InvalidOperation` if this
| :class:`Cursor` has already been used. Only the last call to
| :meth:`where` applied to a :class:`Cursor` has any effect.
|
| .. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code`
| with scope variables. Consider using `$expr`_ instead.
|
| :param code: JavaScript expression to use as a filter
|
| .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/
| .. _$where: https://mongodb.com/docs/manual/reference/operator/query/where/
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Cursor:
|
| collection
| The :class:`~pymongo.collection.Collection` that this
| :class:`Cursor` is iterating.
|
| retrieved
| The number of documents retrieved so far.
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| __exit__(self, exc_type: 'Any', exc_val: 'Any', exc_tb: 'Any') -> 'None'
|
| close(self) -> 'None'
| Explicitly close / kill this cursor.
|
| to_list(self, length: 'Optional[int]' = None) -> 'list[_DocumentType]'
| Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``.
|
| To use::
|
| >>> cursor.to_list()
|
| Or, to read at most n items from the cursor::
|
| >>> cursor.to_list(n)
|
| If the cursor is empty or has no more results, an empty list will be returned.
|
| .. versionadded:: 4.9
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.synchronous.cursor_base._CursorBase:
|
| session
| The cursor's :class:`~pymongo.client_session.ClientSession`, or None.
|
| .. versionadded:: 3.6
|
| ----------------------------------------------------------------------
| Methods inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __del__(self) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| address
| The (host, port) of the server used, or None.
|
| .. versionchanged:: 3.0
| Renamed from "conn_id".
|
| alive
| Does this cursor have the potential to return more data?
|
| This is mostly useful with `tailable cursors
| <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_
| since they will stop iterating even though they *may* return more
| results in the future.
|
| With regular cursors, simply use an asynchronous for loop instead of :attr:`alive`::
|
| async for doc in collection.find():
| print(doc)
|
| .. note:: Even if :attr:`alive` is True, :meth:`next` can raise
| :exc:`StopIteration`. :attr:`alive` can also be True while iterating
| a cursor from a failed server. In this case :attr:`alive` will
| return False after :meth:`next` fails to retrieve the next batch
| of results from the server.
|
| cursor_id
| Returns the id of the cursor.
|
| .. versionadded:: 2.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.cursor_shared._AgnosticCursorBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
__all__ = ['Cursor', 'CursorType', 'RawBatchCursor']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\cursor.py
pymongo.database
Python Library Documentation: module pymongo.database in pymongo
NAME
pymongo.database - Database level operations.
CLASSES
pymongo.common.BaseObject(builtins.object)
pymongo.synchronous.database.Database(pymongo.common.BaseObject, typing.Generic)
typing.Generic(builtins.object)
pymongo.synchronous.database.Database(pymongo.common.BaseObject, typing.Generic)
class Database(pymongo.common.BaseObject, typing.Generic)
| Database(client: 'MongoClient[_DocumentType]', name: 'str', codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'None'
|
| Method resolution order:
| Database
| pymongo.common.BaseObject
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __bool__(self) -> 'NoReturn'
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, name: 'str') -> 'Collection[_DocumentType]'
| Get a collection of this database by name.
|
| Raises InvalidName if an invalid collection name is used.
|
| :param name: the name of the collection to get
|
| __getitem__(self, name: 'str') -> 'Collection[_DocumentType]'
| Get a collection of this database by name.
|
| Raises InvalidName if an invalid collection name is used.
|
| :param name: the name of the collection to get
|
| __hash__(self) -> 'int'
| Return hash(self).
|
| __init__(self, client: 'MongoClient[_DocumentType]', name: 'str', codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'None'
| Get a database by client and name.
|
| Raises :class:`TypeError` if `name` is not an instance of
| :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if
| `name` is not a valid database name.
|
| :param client: A :class:`~pymongo.mongo_client.MongoClient` instance.
| :param name: The database name.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) client.codec_options is used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) client.read_preference is used.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) client.write_concern is used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) client.read_concern is used.
|
| .. seealso:: The MongoDB documentation on `databases <https://dochub.mongodb.org/core/databases>`_.
|
| .. versionchanged:: 4.0
| Removed the eval, system_js, error, last_status, previous_error,
| reset_error_history, authenticate, logout, collection_names,
| current_op, add_user, remove_user, profiling_level,
| set_profiling_level, and profiling_info methods.
| See the :ref:`pymongo4-migration-guide`.
|
| .. versionchanged:: 3.2
| Added the read_concern option.
|
| .. versionchanged:: 3.0
| Added the codec_options, read_preference, and write_concern options.
| :class:`~pymongo.database.Database` no longer returns an instance
| of :class:`~pymongo.collection.Collection` for attribute names
| with leading underscores. You must use dict-style lookups instead::
|
| db['__my_collection__']
|
| Not:
|
| db.__my_collection__
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __next__(self) -> 'NoReturn'
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| aggregate(self, pipeline: '_Pipeline', session: 'Optional[ClientSession]' = None, **kwargs: 'Any') -> 'CommandCursor[_DocumentType]'
| Perform a database-level aggregation.
|
| See the `aggregation pipeline`_ documentation for a list of stages
| that are supported.
|
| .. code-block:: python
|
| # Lists all operations currently running on the server.
| with client.admin.aggregate([{"$currentOp": {}}]) as cursor:
| for operation in cursor:
| print(operation)
|
| The :meth:`aggregate` method obeys the :attr:`read_preference` of this
| :class:`Database`, except when ``$out`` or ``$merge`` are used, in
| which case :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`
| is used.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement.
|
| .. note:: This method does not support the 'explain' option. Please
| use :meth:`~pymongo.database.Database.command` instead.
|
| .. note:: The :attr:`~pymongo.database.Database.write_concern` of
| this collection is automatically applied to this operation.
|
| :param pipeline: a list of aggregation pipeline stages
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param kwargs: extra `aggregate command`_ parameters.
|
| All optional `aggregate command`_ parameters should be passed as
| keyword arguments to this method. Valid options include, but are not
| limited to:
|
| - `allowDiskUse` (bool): Enables writing to temporary files. When set
| to True, aggregation stages can write data to the _tmp subdirectory
| of the --dbpath directory. The default is False.
| - `maxTimeMS` (int): The maximum amount of time to allow the operation
| to run in milliseconds.
| - `batchSize` (int): The maximum number of documents to return per
| batch. Ignored if the connected mongod or mongos does not support
| returning aggregate results using a cursor.
| - `collation` (optional): An instance of
| :class:`~pymongo.collation.Collation`.
| - `let` (dict): A dict of parameter names and values. Values must be
| constant or closed expressions that do not reference document
| fields. Parameters can then be accessed as variables in an
| aggregate expression context (e.g. ``"$$var"``). This option is
| only supported on MongoDB >= 5.0.
|
| :return: A :class:`~pymongo.command_cursor.CommandCursor` over the result
| set.
|
| .. versionadded:: 3.9
|
| .. _aggregation pipeline:
| https://www.mongodb.com/docs/manual/core/aggregation-pipeline/
|
| .. _aggregate command:
| https://mongodb.com/docs/manual/reference/command/aggregate
|
| command(self, command: 'Union[str, MutableMapping[str, Any]]', value: 'Any' = 1, check: 'bool' = True, allowable_errors: 'Optional[Sequence[Union[str, int]]]' = None, read_preference: 'Optional[_ServerMode]' = None, codec_options: 'Optional[bson.codec_options.CodecOptions[_CodecDocumentType]]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'Union[dict[str, Any], _CodecDocumentType]'
| Issue a MongoDB command.
|
| Send command `command` to the database and return the
| response. If `command` is an instance of :class:`str`
| then the command {`command`: `value`} will be sent.
| Otherwise, `command` must be an instance of
| :class:`dict` and will be sent as is.
|
| Any additional keyword arguments will be added to the final
| command document before it is sent.
|
| For example, a command like ``{buildinfo: 1}`` can be sent
| using:
|
| >>> db.command("buildinfo")
| OR
| >>> db.command({"buildinfo": 1})
|
| For a command where the value matters, like ``{count:
| collection_name}`` we can do:
|
| >>> db.command("count", collection_name)
| OR
| >>> db.command({"count": collection_name})
|
| For commands that take additional arguments we can use
| kwargs. So ``{count: collection_name, query: query}`` becomes:
|
| >>> db.command("count", collection_name, query=query)
| OR
| >>> db.command({"count": collection_name, "query": query})
|
| :param command: document representing the command to be issued,
| or the name of the command (for simple commands only).
|
| .. note:: the order of keys in the `command` document is
| significant (the "verb" must come first), so commands
| which require multiple keys (e.g. `findandmodify`)
| should be done with this in mind.
|
| :param value: value to use for the command verb when
| `command` is passed as a string
| :param check: check the response for errors, raising
| :class:`~pymongo.errors.OperationFailure` if there are any
| :param allowable_errors: if `check` is ``True``, error messages
| in this list will be ignored by error-checking
| :param read_preference: The read preference for this
| operation. See :mod:`~pymongo.read_preferences` for options.
| If the provided `session` is in a transaction, defaults to the
| read preference configured for the transaction.
| Otherwise, defaults to
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
| :param codec_options: A :class:`~bson.codec_options.CodecOptions`
| instance.
| :param session: A
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: additional keyword arguments will
| be added to the command document before it is sent
|
|
| .. note:: :meth:`command` does **not** obey this Database's
| :attr:`read_preference` or :attr:`codec_options`. You must use the
| ``read_preference`` and ``codec_options`` parameters instead.
|
| .. note:: :meth:`command` does **not** apply any custom TypeDecoders
| when decoding the command response.
|
| .. note:: If this client has been configured to use MongoDB Stable
| API (see `versioned API <https://www.mongodb.com/docs/manual/reference/stable-api/#what-is-the-stable-api--and-should-you-use-it->`_), then :meth:`command` will
| automatically add API versioning options to the given command.
| Explicitly adding API versioning options in the command and
| declaring an API version on the client is not supported.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.0
| Removed the `as_class`, `fields`, `uuid_subtype`, `tag_sets`,
| and `secondary_acceptable_latency_ms` option.
| Removed `compile_re` option: PyMongo now always represents BSON
| regular expressions as :class:`~bson.regex.Regex` objects. Use
| :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
| BSON regular expression to a Python regular expression object.
| Added the ``codec_options`` parameter.
|
| .. seealso:: The MongoDB documentation on `commands <https://dochub.mongodb.org/core/commands>`_.
|
| create_collection(self, name: 'str', codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None, session: 'Optional[ClientSession]' = None, check_exists: 'Optional[bool]' = True, **kwargs: 'Any') -> 'Collection[_DocumentType]'
| Create a new :class:`~pymongo.collection.Collection` in this
| database.
|
| Normally collection creation is automatic. This method should
| only be used to specify options on
| creation. :class:`~pymongo.errors.CollectionInvalid` will be
| raised if the collection already exists.
|
| :param name: the name of the collection to create
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`Database` is
| used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`Database` is used.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`Database` is
| used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`Database` is
| used.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param check_exists: if True (the default), send a listCollections command to
| check if the collection already exists before creation.
| :param kwargs: additional keyword arguments will
| be passed as options for the `create collection command`_
|
| All optional `create collection command`_ parameters should be passed
| as keyword arguments to this method. Valid options include, but are not
| limited to:
|
| - ``size`` (int): desired initial size for the collection (in
| bytes). For capped collections this size is the max
| size of the collection.
| - ``capped`` (bool): if True, this is a capped collection
| - ``max`` (int): maximum number of objects if capped (optional)
| - ``timeseries`` (dict): a document specifying configuration options for
| timeseries collections
| - ``expireAfterSeconds`` (int): the number of seconds after which a
| document in a timeseries collection expires
| - ``validator`` (dict): a document specifying validation rules or expressions
| for the collection
| - ``validationLevel`` (str): how strictly to apply the
| validation rules to existing documents during an update. The default level
| is "strict"
| - ``validationAction`` (str): whether to "error" on invalid documents
| (the default) or just "warn" about the violations but allow invalid
| documents to be inserted
| - ``indexOptionDefaults`` (dict): a document specifying a default configuration
| for indexes when creating a collection
| - ``viewOn`` (str): the name of the source collection or view from which
| to create the view
| - ``pipeline`` (list): a list of aggregation pipeline stages
| - ``comment`` (str): a user-provided comment to attach to this command.
| This option is only supported on MongoDB >= 4.4.
| - ``encryptedFields`` (dict): **(BETA)** Document that describes the encrypted fields for
| Queryable Encryption. For example::
|
| {
| "escCollection": "enxcol_.encryptedCollection.esc",
| "ecocCollection": "enxcol_.encryptedCollection.ecoc",
| "fields": [
| {
| "path": "firstName",
| "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')),
| "bsonType": "string",
| "queries": {"queryType": "equality"}
| },
| {
| "path": "ssn",
| "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')),
| "bsonType": "string"
| }
| ]
| }
| - ``clusteredIndex`` (dict): Document that specifies the clustered index
| configuration. It must have the following form::
|
| {
| // key pattern must be {_id: 1}
| key: <key pattern>, // required
| unique: <bool>, // required, must be `true`
| name: <string>, // optional, otherwise automatically generated
| v: <int>, // optional, must be `2` if provided
| }
| - ``changeStreamPreAndPostImages`` (dict): a document with a boolean field ``enabled`` for
| enabling pre- and post-images.
|
| .. versionchanged:: 4.2
| Added the ``check_exists``, ``clusteredIndex``, and ``encryptedFields`` parameters.
|
| .. versionchanged:: 3.11
| This method is now supported inside multi-document transactions
| with MongoDB 4.4+.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.4
| Added the collation option.
|
| .. versionchanged:: 3.0
| Added the codec_options, read_preference, and write_concern options.
|
| .. _create collection command:
| https://mongodb.com/docs/manual/reference/command/create
|
| cursor_command(self, command: 'Union[str, MutableMapping[str, Any]]', value: 'Any' = 1, read_preference: 'Optional[_ServerMode]' = None, codec_options: 'Optional[CodecOptions[_CodecDocumentType]]' = None, session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, max_await_time_ms: 'Optional[int]' = None, **kwargs: 'Any') -> 'CommandCursor[_DocumentType]'
| Issue a MongoDB command and parse the response as a cursor.
|
| If the response from the server does not include a cursor field, an error will be thrown.
|
| Otherwise, behaves identically to issuing a normal MongoDB command.
|
| :param command: document representing the command to be issued,
| or the name of the command (for simple commands only).
|
| .. note:: the order of keys in the `command` document is
| significant (the "verb" must come first), so commands
| which require multiple keys (e.g. `findandmodify`)
| should use an instance of :class:`~bson.son.SON` or
| a string and kwargs instead of a Python `dict`.
|
| :param value: value to use for the command verb when
| `command` is passed as a string
| :param read_preference: The read preference for this
| operation. See :mod:`~pymongo.read_preferences` for options.
| If the provided `session` is in a transaction, defaults to the
| read preference configured for the transaction.
| Otherwise, defaults to
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
| :param codec_options: A :class:`~bson.codec_options.CodecOptions`
| instance.
| :param session: A
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to future getMores for this
| command.
| :param max_await_time_ms: The number of ms to wait for more data on future getMores for this command.
| :param kwargs: additional keyword arguments will
| be added to the command document before it is sent
|
| .. note:: :meth:`command` does **not** obey this Database's
| :attr:`read_preference` or :attr:`codec_options`. You must use the
| ``read_preference`` and ``codec_options`` parameters instead.
|
| .. note:: :meth:`command` does **not** apply any custom TypeDecoders
| when decoding the command response.
|
| .. note:: If this client has been configured to use MongoDB Stable
| API (see `versioned API <https://www.mongodb.com/docs/manual/reference/stable-api/#what-is-the-stable-api--and-should-you-use-it->`_), then :meth:`command` will
| automatically add API versioning options to the given command.
| Explicitly adding API versioning options in the command and
| declaring an API version on the client is not supported.
|
| .. seealso:: The MongoDB documentation on `commands <https://dochub.mongodb.org/core/commands>`_.
|
| dereference(self, dbref: 'DBRef', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'Optional[_DocumentType]'
| Dereference a :class:`~bson.dbref.DBRef`, getting the
| document it points to.
|
| Raises :class:`TypeError` if `dbref` is not an instance of
| :class:`~bson.dbref.DBRef`. Returns a document, or ``None`` if
| the reference does not point to a valid document. Raises
| :class:`ValueError` if `dbref` has a database specified that
| is different from the current database.
|
| :param dbref: the reference
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: any additional keyword arguments
| are the same as the arguments to
| :meth:`~pymongo.collection.Collection.find`.
|
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| drop_collection(self, name_or_collection: 'Union[str, Collection[_DocumentTypeArg]]', session: 'Optional[ClientSession]' = None, comment: 'Optional[Any]' = None, encrypted_fields: 'Optional[Mapping[str, Any]]' = None) -> 'dict[str, Any]'
| Drop a collection.
|
| :param name_or_collection: the name of a collection to drop or the
| collection object itself
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param comment: A user-provided comment to attach to this
| command.
| :param encrypted_fields: **(BETA)** Document that describes the encrypted fields for
| Queryable Encryption. For example::
|
| {
| "escCollection": "enxcol_.encryptedCollection.esc",
| "ecocCollection": "enxcol_.encryptedCollection.ecoc",
| "fields": [
| {
| "path": "firstName",
| "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')),
| "bsonType": "string",
| "queries": {"queryType": "equality"}
| },
| {
| "path": "ssn",
| "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')),
| "bsonType": "string"
| }
| ]
|
| }
|
|
| .. note:: The :attr:`~pymongo.database.Database.write_concern` of
| this database is automatically applied to this operation.
|
| .. versionchanged:: 4.2
| Added ``encrypted_fields`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. versionchanged:: 3.4
| Apply this database's write concern automatically to this operation
| when connected to MongoDB >= 3.4.
|
| get_collection(self, name: 'str', codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'Collection[_DocumentType]'
| Get a :class:`~pymongo.collection.Collection` with the given name
| and options.
|
| Useful for creating a :class:`~pymongo.collection.Collection` with
| different codec options, read preference, and/or write concern from
| this :class:`Database`.
|
| >>> db.read_preference
| Primary()
| >>> coll1 = db.test
| >>> coll1.read_preference
| Primary()
| >>> from pymongo import ReadPreference
| >>> coll2 = db.get_collection(
| ... 'test', read_preference=ReadPreference.SECONDARY)
| >>> coll2.read_preference
| Secondary(tag_sets=None)
|
| :param name: The name of the collection - a string.
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`Database` is
| used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`Database` is used. See :mod:`~pymongo.read_preferences`
| for options.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`Database` is
| used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`Database` is
| used.
|
| list_collection_names(self, session: 'Optional[ClientSession]' = None, filter: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'list[str]'
| Get a list of all the collection names in this database.
|
| For example, to list all non-system collections::
|
| filter = {"name": {"$regex": r"^(?!system\.)"}}
| db.list_collection_names(filter=filter)
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param filter: A query document to filter the list of
| collections returned from the listCollections command.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: Optional parameters of the
| `listCollections command
| <https://mongodb.com/docs/manual/reference/command/listCollections/>`_
| can be passed as keyword arguments to this method. The supported
| options differ by server version.
|
|
| .. versionchanged:: 3.8
| Added the ``filter`` and ``**kwargs`` parameters.
|
| .. versionadded:: 3.6
|
| list_collections(self, session: 'Optional[ClientSession]' = None, filter: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, **kwargs: 'Any') -> 'CommandCursor[MutableMapping[str, Any]]'
| Get a cursor over the collections of this database.
|
| Cursors are closed automatically when they are exhausted (the last batch of data is retrieved from the database).
| If a cursor is not exhausted, it will be closed automatically upon garbage collection, which leaves resources open but unused for a potentially long period of time.
| To avoid this, best practice is to call :meth:`Cursor.close` when the cursor is no longer needed,
| or use the cursor in a with statement::
|
| with database.list_collections() as cursor:
| for collection in cursor:
| print(collection)
|
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param filter: A query document to filter the list of
| collections returned from the listCollections command.
| :param comment: A user-provided comment to attach to this
| command.
| :param kwargs: Optional parameters of the
| `listCollections command
| <https://mongodb.com/docs/manual/reference/command/listCollections/>`_
| can be passed as keyword arguments to this method. The supported
| options differ by server version.
|
|
| :return: An instance of :class:`~pymongo.command_cursor.CommandCursor`.
|
| .. versionadded:: 3.6
|
| next = __next__(self) -> 'NoReturn'
|
| validate_collection(self, name_or_collection: 'Union[str, Collection[_DocumentTypeArg]]', scandata: 'bool' = False, full: 'bool' = False, session: 'Optional[ClientSession]' = None, background: 'Optional[bool]' = None, comment: 'Optional[Any]' = None) -> 'dict[str, Any]'
| Validate a collection.
|
| Returns a dict of validation info. Raises CollectionInvalid if
| validation fails.
|
| See also the MongoDB documentation on the `validate command`_.
|
| :param name_or_collection: A Collection object or the name of a
| collection to validate.
| :param scandata: Do extra checks beyond checking the overall
| structure of the collection.
| :param full: Have the server do a more thorough scan of the
| collection. Use with `scandata` for a thorough scan
| of the structure of the collection and the individual
| documents.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param background: A boolean flag that determines whether
| the command runs in the background. Requires MongoDB 4.4+.
| :param comment: A user-provided comment to attach to this
| command.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.11
| Added ``background`` parameter.
|
| .. versionchanged:: 3.6
| Added ``session`` parameter.
|
| .. _validate command: https://mongodb.com/docs/manual/reference/command/validate/
|
| watch(self, pipeline: 'Optional[_Pipeline]' = None, full_document: 'Optional[str]' = None, resume_after: 'Optional[Mapping[str, Any]]' = None, max_await_time_ms: 'Optional[int]' = None, batch_size: 'Optional[int]' = None, collation: 'Optional[_CollationIn]' = None, start_at_operation_time: 'Optional[Timestamp]' = None, session: 'Optional[ClientSession]' = None, start_after: 'Optional[Mapping[str, Any]]' = None, comment: 'Optional[Any]' = None, full_document_before_change: 'Optional[str]' = None, show_expanded_events: 'Optional[bool]' = None) -> 'DatabaseChangeStream[_DocumentType]'
| Watch changes on this database.
|
| Performs an aggregation with an implicit initial ``$changeStream``
| stage and returns a
| :class:`~pymongo.change_stream.DatabaseChangeStream` cursor which
| iterates over changes on all collections in this database.
|
| Introduced in MongoDB 4.0.
|
| .. code-block:: python
|
| with db.watch() as stream:
| for change in stream:
| print(change)
|
| The :class:`~pymongo.change_stream.DatabaseChangeStream` iterable
| blocks until the next change document is returned or an error is
| raised. If the
| :meth:`~pymongo.change_stream.DatabaseChangeStream.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 db.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`_.
|
| :param pipeline: 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.
| :param full_document: The fullDocument to pass as an option
| to the ``$changeStream`` stage. Allowed values: 'updateLookup',
| 'whenAvailable', 'required'. 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.
| :param full_document_before_change: Allowed values: 'whenAvailable'
| and 'required'. Change events may now result in a
| 'fullDocumentBeforeChange' response field.
| :param resume_after: 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.
| :param max_await_time_ms: The maximum time in milliseconds
| for the server to wait for changes before responding to a getMore
| operation.
| :param batch_size: The maximum number of documents to return
| per batch.
| :param collation: The :class:`~pymongo.collation.Collation`
| to use for the aggregation.
| :param start_at_operation_time: 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.
| :param session: a
| :class:`~pymongo.client_session.ClientSession`.
| :param start_after: The same as `resume_after` except that
| `start_after` can resume notifications after an invalidate event.
| This option and `resume_after` are mutually exclusive.
| :param comment: A user-provided comment to attach to this
| command.
| :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.
|
| :return: A :class:`~pymongo.change_stream.DatabaseChangeStream` cursor.
|
| .. versionchanged:: 4.3
| Added `show_expanded_events` parameter.
|
| .. versionchanged:: 4.2
| Added ``full_document_before_change`` parameter.
|
| .. versionchanged:: 4.1
| Added ``comment`` parameter.
|
| .. versionchanged:: 3.9
| Added the ``start_after`` parameter.
|
| .. versionadded:: 3.7
|
| .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.
|
| .. _change streams specification:
| https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
|
| with_options(self, codec_options: 'Optional[CodecOptions[_DocumentTypeArg]]' = None, read_preference: 'Optional[_ServerMode]' = None, write_concern: 'Optional[WriteConcern]' = None, read_concern: 'Optional[ReadConcern]' = None) -> 'Database[_DocumentType] | Database[_DocumentTypeArg]'
| Get a clone of this database changing the specified settings.
|
| >>> db1.read_preference
| Primary()
| >>> from pymongo.read_preferences import Secondary
| >>> db2 = db1.with_options(read_preference=Secondary([{'node': 'analytics'}]))
| >>> db1.read_preference
| Primary()
| >>> db2.read_preference
| Secondary(tag_sets=[{'node': 'analytics'}], max_staleness=-1, hedge=None)
|
| :param codec_options: An instance of
| :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
| default) the :attr:`codec_options` of this :class:`Collection`
| is used.
| :param read_preference: The read preference to use. If
| ``None`` (the default) the :attr:`read_preference` of this
| :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
| for options.
| :param write_concern: An instance of
| :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
| default) the :attr:`write_concern` of this :class:`Collection`
| is used.
| :param read_concern: An instance of
| :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
| default) the :attr:`read_concern` of this :class:`Collection`
| is used.
|
| .. versionadded:: 3.8
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| client
| The client instance for this :class:`Database`.
|
| name
| The name of this :class:`Database`.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __iter__ = None
|
| __orig_bases__ = (<class 'pymongo.common.BaseObject'>, typing.Generic[...
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pymongo.common.BaseObject:
|
| codec_options
| Read only access to the :class:`~bson.codec_options.CodecOptions`
| of this instance.
|
| read_concern
| Read only access to the :class:`~pymongo.read_concern.ReadConcern`
| of this instance.
|
| .. versionadded:: 3.2
|
| read_preference
| Read only access to the read preference of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`read_preference` attribute is now read only.
|
| write_concern
| Read only access to the :class:`~pymongo.write_concern.WriteConcern`
| of this instance.
|
| .. versionchanged:: 3.0
| The :attr:`write_concern` attribute is now read only.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pymongo.common.BaseObject:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
DATA
__all__ = ['Database']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\database.py
pymongo.driver_info
Python Library Documentation: module pymongo.driver_info in pymongo
NAME
pymongo.driver_info - Advanced options for MongoDB drivers implemented on top of PyMongo.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
DriverInfo(builtins.tuple)
DriverInfo
class DriverInfo(DriverInfo)
| DriverInfo(name: 'str', version: 'Optional[str]' = None, platform: 'Optional[str]' = None) -> 'DriverInfo'
|
| Info about a driver wrapping PyMongo.
|
| The MongoDB server logs PyMongo's name, version, and platform whenever
| PyMongo establishes a connection. A driver implemented on top of PyMongo
| can add its own info to this log message. Initialize with three strings
| like 'MyDriver', '1.2.3', 'some platform info'. Any of these strings may be
| None to accept PyMongo's default.
|
| Method resolution order:
| DriverInfo
| DriverInfo
| builtins.tuple
| builtins.object
|
| Static methods defined here:
|
| __new__(cls, name: 'str', version: 'Optional[str]' = None, platform: 'Optional[str]' = None) -> 'DriverInfo'
| Create new instance of DriverInfo(name, version, platform)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Methods inherited from DriverInfo:
|
| __getnewargs__(self) from collections.DriverInfo
| Return self as a plain tuple. Used by copy and pickle.
|
| __repr__(self) from collections.DriverInfo
| Return a nicely formatted representation string
|
| _asdict(self) from collections.DriverInfo
| Return a new dict which maps field names to their values.
|
| _replace(self, /, **kwds) from collections.DriverInfo
| Return a new DriverInfo object replacing specified fields with new values
|
| ----------------------------------------------------------------------
| Class methods inherited from DriverInfo:
|
| _make(iterable) from collections.DriverInfo
| Make a new DriverInfo object from a sequence or iterable
|
| ----------------------------------------------------------------------
| Data descriptors inherited from DriverInfo:
|
| name
| Alias for field number 0
|
| version
| Alias for field number 1
|
| platform
| Alias for field number 2
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from DriverInfo:
|
| __match_args__ = ('name', 'version', 'platform')
|
| _field_defaults = {}
|
| _fields = ('name', 'version', 'platform')
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...)
| See PEP 585
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\driver_info.py
pymongo.errors
Python Library Documentation: module pymongo.errors in pymongo
NAME
pymongo.errors - Exceptions raised by PyMongo.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
bson.errors.InvalidDocument(bson.errors.BSONError)
DocumentTooLarge
builtins.Exception(builtins.BaseException)
PyMongoError
CollectionInvalid
ConfigurationError
InvalidURI
ConnectionFailure
AutoReconnect
NetworkTimeout
NotPrimaryError
ServerSelectionTimeoutError
WaitQueueTimeoutError
EncryptionError
EncryptedCollectionError
InvalidName
InvalidOperation
OperationFailure
BulkWriteError
ClientBulkWriteException
CursorNotFound
ExecutionTimeout
WriteConcernError
WTimeoutError
WriteError
DuplicateKeyError
ProtocolError
class AutoReconnect(ConnectionFailure)
| AutoReconnect(message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
|
| Raised when a connection to the database is lost and an attempt to
| auto-reconnect will be made.
|
| In order to auto-reconnect you must handle this exception, recognizing that
| the operation which caused it has not necessarily succeeded. Future
| operations will attempt to open a new connection to the database (and
| will continue to raise this exception until the first successful
| connection is made).
|
| Subclass of :exc:`~pymongo.errors.ConnectionFailure`.
|
| Method resolution order:
| AutoReconnect
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'details': 'Union[Mapping[str, Any], Sequence[Any]]...
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class BulkWriteError(OperationFailure)
| BulkWriteError(results: '_DocumentOut') -> 'None'
|
| Exception class for bulk write errors.
|
| .. versionadded:: 2.7
|
| Method resolution order:
| BulkWriteError
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, results: '_DocumentOut') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self) -> 'tuple[Any, Any]'
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'details': '_DocumentOut'}
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ClientBulkWriteException(OperationFailure)
| ClientBulkWriteException(results: '_DocumentOut', verbose: 'bool') -> 'None'
|
| Exception class for client-level bulk write errors.
|
| Method resolution order:
| ClientBulkWriteException
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, results: '_DocumentOut', verbose: 'bool') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self) -> 'tuple[Any, Any]'
| Helper for pickle.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| error
| A top-level error that occurred when attempting to
| communicate with the server or execute the bulk write.
|
| This value may not be populated if the exception was
| thrown due to errors occurring on individual writes.
|
| partial_result
| The results of any successful operations that were
| performed before the error was encountered.
|
| write_concern_errors
| Write concern errors that occurred during the bulk write.
|
| This list may have multiple items if more than one
| server command was required to execute the bulk write.
|
| write_errors
| Errors that occurred during the execution of individual write operations.
|
| This list will contain at most one entry if the bulk write was ordered.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'details': '_DocumentOut', 'verbose': 'bool'}
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class CollectionInvalid(PyMongoError)
| CollectionInvalid(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when collection validation fails.
|
| Method resolution order:
| CollectionInvalid
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ConfigurationError(PyMongoError)
| ConfigurationError(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when something is incorrectly configured.
|
| Method resolution order:
| ConfigurationError
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ConnectionFailure(PyMongoError)
| ConnectionFailure(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when a connection to the database cannot be made or is lost.
|
| Method resolution order:
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class CursorNotFound(OperationFailure)
| CursorNotFound(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Raised while iterating query results if the cursor is
| invalidated on the server.
|
| .. versionadded:: 2.7
|
| Method resolution order:
| CursorNotFound
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class DocumentTooLarge(bson.errors.InvalidDocument)
| DocumentTooLarge(message: 'str', document: 'Optional[Any]' = None) -> 'None'
|
| Raised when an encoded document is too large for the connected server.
|
| Method resolution order:
| DocumentTooLarge
| bson.errors.InvalidDocument
| bson.errors.BSONError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods inherited from bson.errors.InvalidDocument:
|
| __init__(self, message: 'str', document: 'Optional[Any]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from bson.errors.InvalidDocument:
|
| document
| The invalid document that caused the error.
|
| ..versionadded:: 4.16
|
| ----------------------------------------------------------------------
| Data descriptors inherited from bson.errors.BSONError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class DuplicateKeyError(WriteError)
| DuplicateKeyError(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Raised when an insert or update fails due to a duplicate key error.
|
| Method resolution order:
| DuplicateKeyError
| WriteError
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class EncryptedCollectionError(EncryptionError)
| EncryptedCollectionError(cause: 'Exception', encrypted_fields: 'Mapping[str, Any]') -> 'None'
|
| Raised when creating a collection with encrypted_fields fails.
|
| .. versionadded:: 4.4
|
| Method resolution order:
| EncryptedCollectionError
| EncryptionError
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, cause: 'Exception', encrypted_fields: 'Mapping[str, Any]') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| encrypted_fields
| The encrypted_fields document that allows inferring which data keys are *known* to be created.
|
| Note that the returned document is not guaranteed to contain information about *all* of the data keys that
| were created, for example in the case of an indefinite error like a timeout. Use the `cause` property to
| determine whether a definite or indefinite error caused this error, and only rely on the accuracy of the
| encrypted_fields if the error is definite.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Readonly properties inherited from EncryptionError:
|
| cause
| The exception that caused this encryption or decryption error.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class EncryptionError(PyMongoError)
| EncryptionError(cause: 'Exception') -> 'None'
|
| Raised when encryption or decryption fails.
|
| This error always wraps another exception which can be retrieved via the
| :attr:`cause` property.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| EncryptionError
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, cause: 'Exception') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| cause
| The exception that caused this encryption or decryption error.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ExecutionTimeout(OperationFailure)
| ExecutionTimeout(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Raised when a database operation times out, exceeding the $maxTimeMS
| set in the query or command option.
|
| .. note:: Requires server version **>= 2.6.0**
|
| .. versionadded:: 2.7
|
| Method resolution order:
| ExecutionTimeout
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class InvalidName(PyMongoError)
| InvalidName(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when an invalid name is used.
|
| Method resolution order:
| InvalidName
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class InvalidOperation(PyMongoError)
| InvalidOperation(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when a client attempts to perform an invalid operation.
|
| Method resolution order:
| InvalidOperation
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class InvalidURI(ConfigurationError)
| InvalidURI(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when trying to parse an invalid mongodb URI.
|
| Method resolution order:
| InvalidURI
| ConfigurationError
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class NetworkTimeout(AutoReconnect)
| NetworkTimeout(message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
|
| An operation on an open connection exceeded socketTimeoutMS.
|
| The remaining connections in the pool stay open. In the case of a write
| operation, you cannot know whether it succeeded or failed.
|
| Subclass of :exc:`~pymongo.errors.AutoReconnect`.
|
| Method resolution order:
| NetworkTimeout
| AutoReconnect
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from AutoReconnect:
|
| __init__(self, message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class NotPrimaryError(AutoReconnect)
| NotPrimaryError(message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], list[Any]]]' = None) -> 'None'
|
| The server responded "not primary" or "node is recovering".
|
| These errors result from a query, write, or command. The operation failed
| because the client thought it was using the primary but the primary has
| stepped down, or the client thought it was using a healthy secondary but
| the secondary is stale and trying to recover.
|
| The client launches a refresh operation on a background thread, to update
| its view of the server as soon as possible after throwing this exception.
|
| Subclass of :exc:`~pymongo.errors.AutoReconnect`.
|
| .. versionadded:: 3.12
|
| Method resolution order:
| NotPrimaryError
| AutoReconnect
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], list[Any]]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class OperationFailure(PyMongoError)
| OperationFailure(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Raised when a database operation fails.
|
| .. versionadded:: 2.7
| The :attr:`details` attribute.
|
| Method resolution order:
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ProtocolError(PyMongoError)
| ProtocolError(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised for failures related to the wire protocol.
|
| Method resolution order:
| ProtocolError
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from PyMongoError:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class PyMongoError(builtins.Exception)
| PyMongoError(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Base class for all PyMongo exceptions.
|
| Method resolution order:
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ServerSelectionTimeoutError(AutoReconnect)
| ServerSelectionTimeoutError(message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
|
| Thrown when no MongoDB server is available for an operation
|
| If there is no suitable server for an operation PyMongo tries for
| ``serverSelectionTimeoutMS`` (default 30 seconds) to find one, then
| throws this exception. For example, it is thrown after attempting an
| operation when PyMongo cannot connect to any server, or if you attempt
| an insert into a replica set that has no primary and does not elect one
| within the timeout window, or if you attempt to query with a Read
| Preference that the replica set cannot satisfy.
|
| Method resolution order:
| ServerSelectionTimeoutError
| AutoReconnect
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from AutoReconnect:
|
| __init__(self, message: 'str' = '', errors: 'Optional[Union[Mapping[str, Any], Sequence[Any]]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class WTimeoutError(WriteConcernError)
| WTimeoutError(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Raised when a database operation times out (i.e. wtimeout expires)
| before replication completes.
|
| With newer versions of MongoDB the `details` attribute may include
| write concern fields like 'n', 'updatedExisting', or 'writtenTo'.
|
| .. versionadded:: 2.7
|
| Method resolution order:
| WTimeoutError
| WriteConcernError
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class WaitQueueTimeoutError(ConnectionFailure)
| WaitQueueTimeoutError(message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
|
| Raised when an operation times out waiting to checkout a connection from the pool.
|
| Subclass of :exc:`~pymongo.errors.ConnectionFailure`.
|
| .. versionadded:: 4.2
|
| Method resolution order:
| WaitQueueTimeoutError
| ConnectionFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Readonly properties defined here:
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| __init__(self, message: 'str' = '', error_labels: 'Optional[Iterable[str]]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class WriteConcernError(OperationFailure)
| WriteConcernError(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Base exception type for errors raised due to write concern.
|
| .. versionadded:: 3.0
|
| Method resolution order:
| WriteConcernError
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class WriteError(OperationFailure)
| WriteError(error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
|
| Base exception type for errors raised during write operations.
|
| .. versionadded:: 3.0
|
| Method resolution order:
| WriteError
| OperationFailure
| PyMongoError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from OperationFailure:
|
| __init__(self, error: 'str', code: 'Optional[int]' = None, details: 'Optional[Mapping[str, Any]]' = None, max_wire_version: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from OperationFailure:
|
| code
| The error code returned by the server, if any.
|
| details
| The complete error document returned by the server.
|
| Depending on the error that occurred, the error document
| may include useful information beyond just the error
| message. When connected to a mongos the error document
| may contain one or more subdocuments if errors occurred
| on multiple shards.
|
| timeout
| True if this error was caused by a timeout.
|
| .. versionadded:: 4.2
|
| ----------------------------------------------------------------------
| Methods inherited from PyMongoError:
|
| has_error_label(self, label: 'str') -> 'bool'
| Return True if this error contains the given label.
|
| .. versionadded:: 3.7
|
| ----------------------------------------------------------------------
| Data descriptors inherited from PyMongoError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
DATA
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\errors.py
pymongo.get_version_string
Python Library Documentation: function get_version_string in module pymongo._version get_version_string() -> 'str'
pymongo.has_c
Python Library Documentation: function has_c in module pymongo.common
has_c() -> 'bool'
Is the C extension installed?
pymongo.hello
Python Library Documentation: module pymongo.hello in pymongo
NAME
pymongo.hello - Helpers for the 'hello' and legacy hello commands.
CLASSES
builtins.object
HelloCompat
typing.Generic(builtins.object)
Hello
class Hello(typing.Generic)
| Hello(doc: '_DocumentType', awaitable: 'bool' = False) -> 'None'
|
| Parse a hello response from the server.
|
| .. versionadded:: 3.12
|
| Method resolution order:
| Hello
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, doc: '_DocumentType', awaitable: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| all_hosts
| List of hosts, passives, and arbiters known to this server.
|
| awaitable
|
| cluster_time
|
| compressors
|
| connection_id
|
| document
| The complete hello command response document.
|
| .. versionadded:: 3.4
|
| election_id
|
| hello_ok
|
| is_readable
|
| is_writable
|
| last_write_date
|
| logical_session_timeout_minutes
|
| max_bson_size
|
| max_message_size
|
| max_wire_version
|
| max_write_batch_size
|
| me
|
| min_wire_version
|
| primary
| This server's opinion about who the primary is, or None.
|
| replica_set_name
| Replica set name or None.
|
| sasl_supported_mechs
| Supported authentication mechanisms for the current user.
|
| For example::
|
| >>> hello.sasl_supported_mechs
| ["SCRAM-SHA-1", "SCRAM-SHA-256"]
|
| server_type
|
| service_id
|
| set_version
|
| speculative_authenticate
| The speculativeAuthenticate field.
|
| tags
| Replica set member tags or empty dict.
|
| topology_version
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class HelloCompat(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CMD = 'hello'
|
| LEGACY_CMD = 'ismaster'
|
| LEGACY_ERROR = 'not master'
|
| LEGACY_PRIMARY = 'ismaster'
|
| PRIMARY = 'isWritablePrimary'
DATA
ClusterTime = typing.Mapping[str, typing.Any]
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\hello.py
pymongo.lock
Python Library Documentation: module pymongo.lock in pymongo
NAME
pymongo.lock - Internal helpers for lock and condition coordination primitives.
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
__annotations__ = {'_forkable_locks': 'weakref.WeakSet[threading.Lock]...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\lock.py
pymongo.logger
Python Library Documentation: module pymongo.logger in pymongo
NAME
pymongo.logger
DESCRIPTION
# Copyright 2023-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
CLASSES
builtins.object
LogMessage
class LogMessage(builtins.object)
| LogMessage(**kwargs: 'Any')
|
| Methods defined here:
|
| __init__(self, **kwargs: 'Any')
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self) -> 'str'
| Return str(self).
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\logger.py
pymongo.max_staleness_selectors
Python Library Documentation: module pymongo.max_staleness_selectors in pymongo
NAME
pymongo.max_staleness_selectors - Criteria to select ServerDescriptions based on maxStalenessSeconds.
DESCRIPTION
The Max Staleness Spec says: When there is a known primary P,
a secondary S's staleness is estimated with this formula:
(S.lastUpdateTime - S.lastWriteDate) - (P.lastUpdateTime - P.lastWriteDate)
+ heartbeatFrequencyMS
When there is no known primary, a secondary S's staleness is estimated with:
SMax.lastWriteDate - S.lastWriteDate + heartbeatFrequencyMS
where "SMax" is the secondary with the greatest lastWriteDate.
FUNCTIONS
select(max_staleness: 'int', selection: 'Selection') -> 'Selection'
Apply max_staleness, in seconds, to a Selection.
DATA
IDLE_WRITE_PERIOD = 10
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
SMALLEST_MAX_STALENESS = 90
TYPE_CHECKING = False
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\max_staleness_selectors.py
pymongo.message
Python Library Documentation: module pymongo.message in pymongo
NAME
pymongo.message
DESCRIPTION
Tools for creating `messages
<https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/>`_ to be sent to
MongoDB.
.. note:: This module is for internal use and is generally not needed by
application developers.
DATA
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
DEFAULT_RAW_BSON_OPTIONS = CodecOptions(document_class=<class 'bson.ra...
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
MAX_INT32 = 2147483647
MIN_INT32 = -2147483648
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
NoReturn = typing.NoReturn
Special type indicating functions that never return.
Example::
from typing import NoReturn
def stop() -> NoReturn:
raise Exception('no way')
NoReturn can also be used as a bottom type, a type that
has no values. Starting in Python 3.11, the Never type should
be used for this concept instead. Type checkers should treat the two
equivalently.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
TYPE_CHECKING = False
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
__annotations__ = {'_UNICODE_REPLACE_CODEC_OPTIONS': 'CodecOptions[Map...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\message.py
pymongo.monitoring
Python Library Documentation: module pymongo.monitoring in pymongo
NAME
pymongo.monitoring - Tools to monitor driver events.
DESCRIPTION
.. versionadded:: 3.1
.. attention:: Starting in PyMongo 3.11, the monitoring classes outlined below
are included in the PyMongo distribution under the
:mod:`~pymongo.event_loggers` submodule.
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
Use :func:`register` to register global listeners for specific events.
Listeners must inherit from one of the abstract classes below and implement
the correct functions for that class.
For example, a simple command logger might be implemented like this::
import logging
from pymongo import monitoring
class CommandLogger(monitoring.CommandListener):
def started(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} started on server "
"{0.connection_id}".format(event))
def succeeded(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"succeeded in {0.duration_micros} "
"microseconds".format(event))
def failed(self, event):
logging.info("Command {0.command_name} with request id "
"{0.request_id} on server {0.connection_id} "
"failed in {0.duration_micros} "
"microseconds".format(event))
monitoring.register(CommandLogger())
Server discovery and monitoring events are also available. For example::
class ServerLogger(monitoring.ServerListener):
def opened(self, event):
logging.info("Server {0.server_address} added to topology "
"{0.topology_id}".format(event))
def description_changed(self, event):
previous_server_type = event.previous_description.server_type
new_server_type = event.new_description.server_type
if new_server_type != previous_server_type:
# server_type_name was added in PyMongo 3.4
logging.info(
"Server {0.server_address} changed type from "
"{0.previous_description.server_type_name} to "
"{0.new_description.server_type_name}".format(event))
def closed(self, event):
logging.warning("Server {0.server_address} removed from topology "
"{0.topology_id}".format(event))
class HeartbeatLogger(monitoring.ServerHeartbeatListener):
def started(self, event):
logging.info("Heartbeat sent to server "
"{0.connection_id}".format(event))
def succeeded(self, event):
# The reply.document attribute was added in PyMongo 3.4.
logging.info("Heartbeat to server {0.connection_id} "
"succeeded with reply "
"{0.reply.document}".format(event))
def failed(self, event):
logging.warning("Heartbeat to server {0.connection_id} "
"failed with error {0.reply}".format(event))
class TopologyLogger(monitoring.TopologyListener):
def opened(self, event):
logging.info("Topology with id {0.topology_id} "
"opened".format(event))
def description_changed(self, event):
logging.info("Topology description updated for "
"topology id {0.topology_id}".format(event))
previous_topology_type = event.previous_description.topology_type
new_topology_type = event.new_description.topology_type
if new_topology_type != previous_topology_type:
# topology_type_name was added in PyMongo 3.4
logging.info(
"Topology {0.topology_id} changed type from "
"{0.previous_description.topology_type_name} to "
"{0.new_description.topology_type_name}".format(event))
# The has_writable_server and has_readable_server methods
# were added in PyMongo 3.4.
if not event.new_description.has_writable_server():
logging.warning("No writable servers available.")
if not event.new_description.has_readable_server():
logging.warning("No readable servers available.")
def closed(self, event):
logging.info("Topology with id {0.topology_id} "
"closed".format(event))
Connection monitoring and pooling events are also available. For example::
class ConnectionPoolLogger(ConnectionPoolListener):
def pool_created(self, event):
logging.info("[pool {0.address}] pool created".format(event))
def pool_ready(self, event):
logging.info("[pool {0.address}] pool is ready".format(event))
def pool_cleared(self, event):
logging.info("[pool {0.address}] pool cleared".format(event))
def pool_closed(self, event):
logging.info("[pool {0.address}] pool closed".format(event))
def connection_created(self, event):
logging.info("[pool {0.address}][connection #{0.connection_id}] "
"connection created".format(event))
def connection_ready(self, event):
logging.info("[pool {0.address}][connection #{0.connection_id}] "
"connection setup succeeded".format(event))
def connection_closed(self, event):
logging.info("[pool {0.address}][connection #{0.connection_id}] "
"connection closed, reason: "
"{0.reason}".format(event))
def connection_check_out_started(self, event):
logging.info("[pool {0.address}] connection check out "
"started".format(event))
def connection_check_out_failed(self, event):
logging.info("[pool {0.address}] connection check out "
"failed, reason: {0.reason}".format(event))
def connection_checked_out(self, event):
logging.info("[pool {0.address}][connection #{0.connection_id}] "
"connection checked out of pool".format(event))
def connection_checked_in(self, event):
logging.info("[pool {0.address}][connection #{0.connection_id}] "
"connection checked into pool".format(event))
Event listeners can also be registered per instance of
:class:`~pymongo.mongo_client.MongoClient`::
client = MongoClient(event_listeners=[CommandLogger()])
Note that previously registered global listeners are automatically included
when configuring per client event listeners. Registering a new global listener
will not add that listener to existing client instances.
.. note:: Events are delivered **synchronously**. Application threads block
waiting for event handlers (e.g. :meth:`~CommandListener.started`) to
return. Care must be taken to ensure that your event handlers are efficient
enough to not adversely affect overall application performance.
.. warning:: The command documents published through this API are *not* copies.
If you intend to modify them in any way you must copy them in your event
handler first.
CLASSES
builtins.object
ConnectionCheckOutFailedReason
ConnectionClosedReason
TopologyEvent
TopologyClosedEvent
TopologyDescriptionChangedEvent
TopologyOpenedEvent
_CommandEvent(builtins.object)
CommandFailedEvent
CommandStartedEvent
CommandSucceededEvent
_ConnectionDurationEvent(_ConnectionIdEvent)
ConnectionCheckOutFailedEvent
ConnectionCheckedOutEvent
ConnectionReadyEvent
_ConnectionEvent(builtins.object)
ConnectionCheckOutStartedEvent
_ConnectionIdEvent(_ConnectionEvent)
ConnectionCheckedInEvent
ConnectionClosedEvent
ConnectionCreatedEvent
_EventListener(builtins.object)
CommandListener
ConnectionPoolListener
ServerHeartbeatListener
ServerListener
TopologyListener
_PoolEvent(builtins.object)
PoolClearedEvent
PoolClosedEvent
PoolCreatedEvent
PoolReadyEvent
_ServerEvent(builtins.object)
ServerClosedEvent
ServerDescriptionChangedEvent
ServerOpeningEvent
_ServerHeartbeatEvent(builtins.object)
ServerHeartbeatFailedEvent
ServerHeartbeatStartedEvent
ServerHeartbeatSucceededEvent
class CommandFailedEvent(_CommandEvent)
| CommandFailedEvent(duration: 'datetime.timedelta', failure: '_DocumentOut', command_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, database_name: 'str' = '', server_connection_id: 'Optional[int]' = None) -> 'None'
|
| Event published when a command fails.
|
| :param duration: The command duration as a datetime.timedelta.
| :param failure: The server reply document.
| :param command_name: The command name.
| :param request_id: The request id for this operation.
| :param connection_id: The address (host, port) of the server this command
| was sent to.
| :param operation_id: An optional identifier for a series of related events.
| :param service_id: The service_id this command was sent to, or ``None``.
| :param database_name: The database this command was sent to, or ``""``.
|
| Method resolution order:
| CommandFailedEvent
| _CommandEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, duration: 'datetime.timedelta', failure: '_DocumentOut', command_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, database_name: 'str' = '', server_connection_id: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| duration_micros
| The duration of this operation in microseconds.
|
| failure
| The server failure document for this operation.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _CommandEvent:
|
| command_name
| The command name.
|
| connection_id
| The address (host, port) of the server this command was sent to.
|
| database_name
| The database_name this command was sent to, or ``""``.
|
| .. versionadded:: 4.6
|
| operation_id
| An id for this series of events or None.
|
| request_id
| The request id for this operation.
|
| server_connection_id
| The server-side connection id for the connection this command was sent on, or ``None``.
|
| .. versionadded:: 4.7
|
| service_id
| The service_id this command was sent to, or ``None``.
|
| .. versionadded:: 3.12
class CommandListener(_EventListener)
| Abstract base class for command listeners.
|
| Handles `CommandStartedEvent`, `CommandSucceededEvent`,
| and `CommandFailedEvent`.
|
| Method resolution order:
| CommandListener
| _EventListener
| builtins.object
|
| Methods defined here:
|
| failed(self, event: 'CommandFailedEvent') -> 'None'
| Abstract method to handle a `CommandFailedEvent`.
|
| :param event: An instance of :class:`CommandFailedEvent`.
|
| started(self, event: 'CommandStartedEvent') -> 'None'
| Abstract method to handle a `CommandStartedEvent`.
|
| :param event: An instance of :class:`CommandStartedEvent`.
|
| succeeded(self, event: 'CommandSucceededEvent') -> 'None'
| Abstract method to handle a `CommandSucceededEvent`.
|
| :param event: An instance of :class:`CommandSucceededEvent`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _EventListener:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class CommandStartedEvent(_CommandEvent)
| CommandStartedEvent(command: '_DocumentOut', database_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, server_connection_id: 'Optional[int]' = None) -> 'None'
|
| Event published when a command starts.
|
| :param command: The command document.
| :param database_name: The name of the database this command was run against.
| :param request_id: The request id for this operation.
| :param connection_id: The address (host, port) of the server this command
| was sent to.
| :param operation_id: An optional identifier for a series of related events.
| :param service_id: The service_id this command was sent to, or ``None``.
|
| Method resolution order:
| CommandStartedEvent
| _CommandEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, command: '_DocumentOut', database_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, server_connection_id: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| command
| The command document.
|
| database_name
| The name of the database this command was run against.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _CommandEvent:
|
| command_name
| The command name.
|
| connection_id
| The address (host, port) of the server this command was sent to.
|
| operation_id
| An id for this series of events or None.
|
| request_id
| The request id for this operation.
|
| server_connection_id
| The server-side connection id for the connection this command was sent on, or ``None``.
|
| .. versionadded:: 4.7
|
| service_id
| The service_id this command was sent to, or ``None``.
|
| .. versionadded:: 3.12
class CommandSucceededEvent(_CommandEvent)
| CommandSucceededEvent(duration: 'datetime.timedelta', reply: '_DocumentOut', command_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, database_name: 'str' = '', server_connection_id: 'Optional[int]' = None) -> 'None'
|
| Event published when a command succeeds.
|
| :param duration: The command duration as a datetime.timedelta.
| :param reply: The server reply document.
| :param command_name: The command name.
| :param request_id: The request id for this operation.
| :param connection_id: The address (host, port) of the server this command
| was sent to.
| :param operation_id: An optional identifier for a series of related events.
| :param service_id: The service_id this command was sent to, or ``None``.
| :param database_name: The database this command was sent to, or ``""``.
|
| Method resolution order:
| CommandSucceededEvent
| _CommandEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, duration: 'datetime.timedelta', reply: '_DocumentOut', command_name: 'str', request_id: 'int', connection_id: '_Address', operation_id: 'Optional[int]', service_id: 'Optional[ObjectId]' = None, database_name: 'str' = '', server_connection_id: 'Optional[int]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| duration_micros
| The duration of this operation in microseconds.
|
| reply
| The server failure document for this operation.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _CommandEvent:
|
| command_name
| The command name.
|
| connection_id
| The address (host, port) of the server this command was sent to.
|
| database_name
| The database_name this command was sent to, or ``""``.
|
| .. versionadded:: 4.6
|
| operation_id
| An id for this series of events or None.
|
| request_id
| The request id for this operation.
|
| server_connection_id
| The server-side connection id for the connection this command was sent on, or ``None``.
|
| .. versionadded:: 4.7
|
| service_id
| The service_id this command was sent to, or ``None``.
|
| .. versionadded:: 3.12
class ConnectionCheckOutFailedEvent(_ConnectionDurationEvent)
| ConnectionCheckOutFailedEvent(address: '_Address', reason: 'str', duration: 'Optional[float]') -> 'None'
|
| Published when the driver's attempt to check out a connection fails.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param reason: A reason explaining why connection check out failed.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionCheckOutFailedEvent
| _ConnectionDurationEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, address: '_Address', reason: 'str', duration: 'Optional[float]') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| reason
| A reason explaining why connection check out failed.
|
| The reason must be one of the strings from the
| :class:`ConnectionCheckOutFailedReason` enum.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionDurationEvent:
|
| duration
| The duration of the connection event.
|
| .. versionadded:: 4.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionCheckOutFailedReason(builtins.object)
| An enum that defines values for `reason` on a
| :class:`ConnectionCheckOutFailedEvent`.
|
| .. versionadded:: 3.9
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| CONN_ERROR = 'connectionError'
|
| POOL_CLOSED = 'poolClosed'
|
| TIMEOUT = 'timeout'
class ConnectionCheckOutStartedEvent(_ConnectionEvent)
| ConnectionCheckOutStartedEvent(address: '_Address') -> 'None'
|
| Published when the driver starts attempting to check out a connection.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionCheckOutStartedEvent
| _ConnectionEvent
| builtins.object
|
| Methods inherited from _ConnectionEvent:
|
| __init__(self, address: '_Address') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionCheckedInEvent(_ConnectionIdEvent)
| ConnectionCheckedInEvent(address: '_Address', connection_id: 'int') -> 'None'
|
| Published when the driver checks in a Connection into the Pool.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param connection_id: The integer ID of the Connection in this Pool.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionCheckedInEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods inherited from _ConnectionIdEvent:
|
| __init__(self, address: '_Address', connection_id: 'int') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionCheckedOutEvent(_ConnectionDurationEvent)
| ConnectionCheckedOutEvent(address: '_Address', connection_id: 'int', duration: 'Optional[float]') -> 'None'
|
| Published when the driver successfully checks out a connection.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param connection_id: The integer ID of the Connection in this Pool.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionCheckedOutEvent
| _ConnectionDurationEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods inherited from _ConnectionDurationEvent:
|
| __init__(self, address: '_Address', connection_id: 'int', duration: 'Optional[float]') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionDurationEvent:
|
| duration
| The duration of the connection event.
|
| .. versionadded:: 4.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionClosedEvent(_ConnectionIdEvent)
| ConnectionClosedEvent(address: '_Address', connection_id: 'int', reason: 'str')
|
| Published when a Connection is closed.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param connection_id: The integer ID of the Connection in this Pool.
| :param reason: A reason explaining why this connection was closed.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionClosedEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, address: '_Address', connection_id: 'int', reason: 'str')
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| reason
| A reason explaining why this connection was closed.
|
| The reason must be one of the strings from the
| :class:`ConnectionClosedReason` enum.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionClosedReason(builtins.object)
| An enum that defines values for `reason` on a
| :class:`ConnectionClosedEvent`.
|
| .. versionadded:: 3.9
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| ERROR = 'error'
|
| IDLE = 'idle'
|
| POOL_CLOSED = 'poolClosed'
|
| STALE = 'stale'
class ConnectionCreatedEvent(_ConnectionIdEvent)
| ConnectionCreatedEvent(address: '_Address', connection_id: 'int') -> 'None'
|
| Published when a Connection Pool creates a Connection object.
|
| NOTE: This connection is not ready for use until the
| :class:`ConnectionReadyEvent` is published.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param connection_id: The integer ID of the Connection in this Pool.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionCreatedEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods inherited from _ConnectionIdEvent:
|
| __init__(self, address: '_Address', connection_id: 'int') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class ConnectionPoolListener(_EventListener)
| Abstract base class for connection pool listeners.
|
| Handles all of the connection pool events defined in the Connection
| Monitoring and Pooling Specification:
| :class:`PoolCreatedEvent`, :class:`PoolClearedEvent`,
| :class:`PoolClosedEvent`, :class:`ConnectionCreatedEvent`,
| :class:`ConnectionReadyEvent`, :class:`ConnectionClosedEvent`,
| :class:`ConnectionCheckOutStartedEvent`,
| :class:`ConnectionCheckOutFailedEvent`,
| :class:`ConnectionCheckedOutEvent`,
| and :class:`ConnectionCheckedInEvent`.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionPoolListener
| _EventListener
| builtins.object
|
| Methods defined here:
|
| connection_check_out_failed(self, event: 'ConnectionCheckOutFailedEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionCheckOutFailedEvent`.
|
| Emitted when the driver's attempt to check out a connection fails.
|
| :param event: An instance of :class:`ConnectionCheckOutFailedEvent`.
|
| connection_check_out_started(self, event: 'ConnectionCheckOutStartedEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionCheckOutStartedEvent`.
|
| Emitted when the driver starts attempting to check out a connection.
|
| :param event: An instance of :class:`ConnectionCheckOutStartedEvent`.
|
| connection_checked_in(self, event: 'ConnectionCheckedInEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionCheckedInEvent`.
|
| Emitted when the driver checks in a connection back to the connection
| Pool.
|
| :param event: An instance of :class:`ConnectionCheckedInEvent`.
|
| connection_checked_out(self, event: 'ConnectionCheckedOutEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionCheckedOutEvent`.
|
| Emitted when the driver successfully checks out a connection.
|
| :param event: An instance of :class:`ConnectionCheckedOutEvent`.
|
| connection_closed(self, event: 'ConnectionClosedEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionClosedEvent`.
|
| Emitted when a connection Pool closes a connection.
|
| :param event: An instance of :class:`ConnectionClosedEvent`.
|
| connection_created(self, event: 'ConnectionCreatedEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionCreatedEvent`.
|
| Emitted when a connection Pool creates a Connection object.
|
| :param event: An instance of :class:`ConnectionCreatedEvent`.
|
| connection_ready(self, event: 'ConnectionReadyEvent') -> 'None'
| Abstract method to handle a :class:`ConnectionReadyEvent`.
|
| Emitted when a connection has finished its setup, and is now ready to
| use.
|
| :param event: An instance of :class:`ConnectionReadyEvent`.
|
| pool_cleared(self, event: 'PoolClearedEvent') -> 'None'
| Abstract method to handle a `PoolClearedEvent`.
|
| Emitted when a connection Pool is cleared.
|
| :param event: An instance of :class:`PoolClearedEvent`.
|
| pool_closed(self, event: 'PoolClosedEvent') -> 'None'
| Abstract method to handle a `PoolClosedEvent`.
|
| Emitted when a connection Pool is closed.
|
| :param event: An instance of :class:`PoolClosedEvent`.
|
| pool_created(self, event: 'PoolCreatedEvent') -> 'None'
| Abstract method to handle a :class:`PoolCreatedEvent`.
|
| Emitted when a connection Pool is created.
|
| :param event: An instance of :class:`PoolCreatedEvent`.
|
| pool_ready(self, event: 'PoolReadyEvent') -> 'None'
| Abstract method to handle a :class:`PoolReadyEvent`.
|
| Emitted when a connection Pool is marked ready.
|
| :param event: An instance of :class:`PoolReadyEvent`.
|
| .. versionadded:: 4.0
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _EventListener:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ConnectionReadyEvent(_ConnectionDurationEvent)
| ConnectionReadyEvent(address: '_Address', connection_id: 'int', duration: 'Optional[float]') -> 'None'
|
| Published when a Connection has finished its setup, and is ready to use.
|
| :param address: The address (host, port) pair of the server this
| Connection is attempting to connect to.
| :param connection_id: The integer ID of the Connection in this Pool.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| ConnectionReadyEvent
| _ConnectionDurationEvent
| _ConnectionIdEvent
| _ConnectionEvent
| builtins.object
|
| Methods inherited from _ConnectionDurationEvent:
|
| __init__(self, address: '_Address', connection_id: 'int', duration: 'Optional[float]') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionDurationEvent:
|
| duration
| The duration of the connection event.
|
| .. versionadded:: 4.7
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionIdEvent:
|
| connection_id
| The ID of the connection.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ConnectionEvent:
|
| address
| The address (host, port) pair of the server this connection is
| attempting to connect to.
class PoolClearedEvent(_PoolEvent)
| PoolClearedEvent(address: '_Address', service_id: 'Optional[ObjectId]' = None, interrupt_connections: 'bool' = False) -> 'None'
|
| Published when a Connection Pool is cleared.
|
| :param address: The address (host, port) pair of the server this Pool is
| attempting to connect to.
| :param service_id: The service_id this command was sent to, or ``None``.
| :param interrupt_connections: True if all active connections were interrupted by the Pool during clearing.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| PoolClearedEvent
| _PoolEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, address: '_Address', service_id: 'Optional[ObjectId]' = None, interrupt_connections: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| interrupt_connections
| If True, active connections are interrupted during clearing.
|
| .. versionadded:: 4.7
|
| service_id
| Connections with this service_id are cleared.
|
| When service_id is ``None``, all connections in the pool are cleared.
|
| .. versionadded:: 3.12
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _PoolEvent:
|
| address
| The address (host, port) pair of the server the pool is attempting
| to connect to.
class PoolClosedEvent(_PoolEvent)
| PoolClosedEvent(address: '_Address') -> 'None'
|
| Published when a Connection Pool is closed.
|
| :param address: The address (host, port) pair of the server this Pool is
| attempting to connect to.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| PoolClosedEvent
| _PoolEvent
| builtins.object
|
| Methods inherited from _PoolEvent:
|
| __init__(self, address: '_Address') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _PoolEvent:
|
| address
| The address (host, port) pair of the server the pool is attempting
| to connect to.
class PoolCreatedEvent(_PoolEvent)
| PoolCreatedEvent(address: '_Address', options: 'dict[str, Any]') -> 'None'
|
| Published when a Connection Pool is created.
|
| :param address: The address (host, port) pair of the server this Pool is
| attempting to connect to.
|
| .. versionadded:: 3.9
|
| Method resolution order:
| PoolCreatedEvent
| _PoolEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, address: '_Address', options: 'dict[str, Any]') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| options
| Any non-default pool options that were set on this Connection Pool.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _PoolEvent:
|
| address
| The address (host, port) pair of the server the pool is attempting
| to connect to.
class PoolReadyEvent(_PoolEvent)
| PoolReadyEvent(address: '_Address') -> 'None'
|
| Published when a Connection Pool is marked ready.
|
| :param address: The address (host, port) pair of the server this Pool is
| attempting to connect to.
|
| .. versionadded:: 4.0
|
| Method resolution order:
| PoolReadyEvent
| _PoolEvent
| builtins.object
|
| Methods inherited from _PoolEvent:
|
| __init__(self, address: '_Address') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _PoolEvent:
|
| address
| The address (host, port) pair of the server the pool is attempting
| to connect to.
class ServerClosedEvent(_ServerEvent)
| ServerClosedEvent(server_address: '_Address', topology_id: 'ObjectId') -> 'None'
|
| Published when server is closed.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerClosedEvent
| _ServerEvent
| builtins.object
|
| Methods inherited from _ServerEvent:
|
| __init__(self, server_address: '_Address', topology_id: 'ObjectId') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerEvent:
|
| server_address
| The address (host, port) pair of the server
|
| topology_id
| A unique identifier for the topology this server is a part of.
class ServerDescriptionChangedEvent(_ServerEvent)
| ServerDescriptionChangedEvent(previous_description: 'ServerDescription', new_description: 'ServerDescription', *args: 'Any') -> 'None'
|
| Published when server description changes.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerDescriptionChangedEvent
| _ServerEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, previous_description: 'ServerDescription', new_description: 'ServerDescription', *args: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| new_description
| The new
| :class:`~pymongo.server_description.ServerDescription`.
|
| previous_description
| The previous
| :class:`~pymongo.server_description.ServerDescription`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerEvent:
|
| server_address
| The address (host, port) pair of the server
|
| topology_id
| A unique identifier for the topology this server is a part of.
class ServerHeartbeatFailedEvent(_ServerHeartbeatEvent)
| ServerHeartbeatFailedEvent(duration: 'float', reply: 'Exception', connection_id: '_Address', awaited: 'bool' = False) -> 'None'
|
| Fired when the server heartbeat fails, either with an "ok: 0"
| or a socket exception.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerHeartbeatFailedEvent
| _ServerHeartbeatEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, duration: 'float', reply: 'Exception', connection_id: '_Address', awaited: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| awaited
| Whether the heartbeat was awaited.
|
| If true, then :meth:`duration` reflects the sum of the round trip time
| to the server and the time that the server waited before sending a
| response.
|
| .. versionadded:: 3.11
|
| duration
| The duration of this heartbeat in microseconds.
|
| reply
| A subclass of :exc:`Exception`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerHeartbeatEvent:
|
| connection_id
| The address (host, port) of the server this heartbeat was sent
| to.
class ServerHeartbeatListener(_EventListener)
| Abstract base class for server heartbeat listeners.
|
| Handles `ServerHeartbeatStartedEvent`, `ServerHeartbeatSucceededEvent`,
| and `ServerHeartbeatFailedEvent`.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerHeartbeatListener
| _EventListener
| builtins.object
|
| Methods defined here:
|
| failed(self, event: 'ServerHeartbeatFailedEvent') -> 'None'
| Abstract method to handle a `ServerHeartbeatFailedEvent`.
|
| :param event: An instance of :class:`ServerHeartbeatFailedEvent`.
|
| started(self, event: 'ServerHeartbeatStartedEvent') -> 'None'
| Abstract method to handle a `ServerHeartbeatStartedEvent`.
|
| :param event: An instance of :class:`ServerHeartbeatStartedEvent`.
|
| succeeded(self, event: 'ServerHeartbeatSucceededEvent') -> 'None'
| Abstract method to handle a `ServerHeartbeatSucceededEvent`.
|
| :param event: An instance of :class:`ServerHeartbeatSucceededEvent`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _EventListener:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ServerHeartbeatStartedEvent(_ServerHeartbeatEvent)
| ServerHeartbeatStartedEvent(connection_id: '_Address', awaited: 'bool' = False) -> 'None'
|
| Published when a heartbeat is started.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerHeartbeatStartedEvent
| _ServerHeartbeatEvent
| builtins.object
|
| Methods inherited from _ServerHeartbeatEvent:
|
| __init__(self, connection_id: '_Address', awaited: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerHeartbeatEvent:
|
| awaited
| Whether the heartbeat was issued as an awaitable hello command.
|
| .. versionadded:: 4.6
|
| connection_id
| The address (host, port) of the server this heartbeat was sent
| to.
class ServerHeartbeatSucceededEvent(_ServerHeartbeatEvent)
| ServerHeartbeatSucceededEvent(duration: 'float', reply: 'Hello[dict[str, Any]]', connection_id: '_Address', awaited: 'bool' = False) -> 'None'
|
| Fired when the server heartbeat succeeds.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerHeartbeatSucceededEvent
| _ServerHeartbeatEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, duration: 'float', reply: 'Hello[dict[str, Any]]', connection_id: '_Address', awaited: 'bool' = False) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| awaited
| Whether the heartbeat was awaited.
|
| If true, then :meth:`duration` reflects the sum of the round trip time
| to the server and the time that the server waited before sending a
| response.
|
| .. versionadded:: 3.11
|
| duration
| The duration of this heartbeat in microseconds.
|
| reply
| An instance of :class:`~pymongo.hello.Hello`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerHeartbeatEvent:
|
| connection_id
| The address (host, port) of the server this heartbeat was sent
| to.
class ServerListener(_EventListener)
| Abstract base class for server listeners.
| Handles `ServerOpeningEvent`, `ServerDescriptionChangedEvent`, and
| `ServerClosedEvent`.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerListener
| _EventListener
| builtins.object
|
| Methods defined here:
|
| closed(self, event: 'ServerClosedEvent') -> 'None'
| Abstract method to handle a `ServerClosedEvent`.
|
| :param event: An instance of :class:`ServerClosedEvent`.
|
| description_changed(self, event: 'ServerDescriptionChangedEvent') -> 'None'
| Abstract method to handle a `ServerDescriptionChangedEvent`.
|
| :param event: An instance of :class:`ServerDescriptionChangedEvent`.
|
| opened(self, event: 'ServerOpeningEvent') -> 'None'
| Abstract method to handle a `ServerOpeningEvent`.
|
| :param event: An instance of :class:`ServerOpeningEvent`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _EventListener:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ServerOpeningEvent(_ServerEvent)
| ServerOpeningEvent(server_address: '_Address', topology_id: 'ObjectId') -> 'None'
|
| Published when server is initialized.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| ServerOpeningEvent
| _ServerEvent
| builtins.object
|
| Methods inherited from _ServerEvent:
|
| __init__(self, server_address: '_Address', topology_id: 'ObjectId') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerEvent:
|
| server_address
| The address (host, port) pair of the server
|
| topology_id
| A unique identifier for the topology this server is a part of.
class TopologyClosedEvent(TopologyEvent)
| TopologyClosedEvent(topology_id: 'ObjectId') -> 'None'
|
| Published when the topology is closed.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| TopologyClosedEvent
| TopologyEvent
| builtins.object
|
| Methods inherited from TopologyEvent:
|
| __init__(self, topology_id: 'ObjectId') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from TopologyEvent:
|
| topology_id
| A unique identifier for the topology this server is a part of.
class TopologyDescriptionChangedEvent(TopologyEvent)
| TopologyDescriptionChangedEvent(previous_description: 'TopologyDescription', new_description: 'TopologyDescription', *args: 'Any') -> 'None'
|
| Published when the topology description changes.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| TopologyDescriptionChangedEvent
| TopologyEvent
| builtins.object
|
| Methods defined here:
|
| __init__(self, previous_description: 'TopologyDescription', new_description: 'TopologyDescription', *args: 'Any') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| new_description
| The new
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| previous_description
| The previous
| :class:`~pymongo.topology_description.TopologyDescription`.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from TopologyEvent:
|
| topology_id
| A unique identifier for the topology this server is a part of.
class TopologyEvent(builtins.object)
| TopologyEvent(topology_id: 'ObjectId') -> 'None'
|
| Base class for topology description events.
|
| Methods defined here:
|
| __init__(self, topology_id: 'ObjectId') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| topology_id
| A unique identifier for the topology this server is a part of.
class TopologyListener(_EventListener)
| Abstract base class for topology monitoring listeners.
| Handles `TopologyOpenedEvent`, `TopologyDescriptionChangedEvent`, and
| `TopologyClosedEvent`.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| TopologyListener
| _EventListener
| builtins.object
|
| Methods defined here:
|
| closed(self, event: 'TopologyClosedEvent') -> 'None'
| Abstract method to handle a `TopologyClosedEvent`.
|
| :param event: An instance of :class:`TopologyClosedEvent`.
|
| description_changed(self, event: 'TopologyDescriptionChangedEvent') -> 'None'
| Abstract method to handle a `TopologyDescriptionChangedEvent`.
|
| :param event: An instance of :class:`TopologyDescriptionChangedEvent`.
|
| opened(self, event: 'TopologyOpenedEvent') -> 'None'
| Abstract method to handle a `TopologyOpenedEvent`.
|
| :param event: An instance of :class:`TopologyOpenedEvent`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _EventListener:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class TopologyOpenedEvent(TopologyEvent)
| TopologyOpenedEvent(topology_id: 'ObjectId') -> 'None'
|
| Published when the topology is initialized.
|
| .. versionadded:: 3.3
|
| Method resolution order:
| TopologyOpenedEvent
| TopologyEvent
| builtins.object
|
| Methods inherited from TopologyEvent:
|
| __init__(self, topology_id: 'ObjectId') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from TopologyEvent:
|
| topology_id
| A unique identifier for the topology this server is a part of.
FUNCTIONS
register(listener: '_EventListener') -> 'None'
Register a global event listener.
:param listener: A subclasses of :class:`CommandListener`,
:class:`ServerHeartbeatListener`, :class:`ServerListener`,
:class:`TopologyListener`, or :class:`ConnectionPoolListener`.
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\monitoring.py
pymongo.network_layer
Python Library Documentation: module pymongo.network_layer in pymongo
NAME
pymongo.network_layer - Internal network layer helper methods.
CLASSES
asyncio.protocols.BufferedProtocol(asyncio.protocols.BaseProtocol)
PyMongoProtocol
builtins.object
NetworkingInterfaceBase
AsyncNetworkingInterface
NetworkingInterface
class AsyncNetworkingInterface(NetworkingInterfaceBase)
| AsyncNetworkingInterface(conn: 'tuple[Transport, PyMongoProtocol]')
|
| Method resolution order:
| AsyncNetworkingInterface
| NetworkingInterfaceBase
| builtins.object
|
| Methods defined here:
|
| __init__(self, conn: 'tuple[Transport, PyMongoProtocol]')
| Initialize self. See help(type(self)) for accurate signature.
|
| async close(self) -> 'None'
|
| is_closing(self) -> 'bool'
|
| settimeout(self, timeout: 'float | None') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| get_conn
|
| gettimeout
|
| sock
|
| ----------------------------------------------------------------------
| Data descriptors inherited from NetworkingInterfaceBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class NetworkingInterface(NetworkingInterfaceBase)
| NetworkingInterface(conn: 'Union[socket.socket, _sslConn]')
|
| Method resolution order:
| NetworkingInterface
| NetworkingInterfaceBase
| builtins.object
|
| Methods defined here:
|
| __init__(self, conn: 'Union[socket.socket, _sslConn]')
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self) -> 'None'
|
| fileno(self) -> 'int'
|
| gettimeout(self) -> 'float | None'
|
| is_closing(self) -> 'bool'
|
| recv_into(self, buffer: 'bytes | memoryview') -> 'int'
|
| settimeout(self, timeout: 'float | None') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| get_conn
|
| sock
|
| ----------------------------------------------------------------------
| Data descriptors inherited from NetworkingInterfaceBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class NetworkingInterfaceBase(builtins.object)
| NetworkingInterfaceBase(conn: 'Any')
|
| Methods defined here:
|
| __init__(self, conn: 'Any')
| Initialize self. See help(type(self)) for accurate signature.
|
| close(self) -> 'Any'
|
| is_closing(self) -> 'bool'
|
| settimeout(self, timeout: 'float | None') -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| get_conn
|
| gettimeout
|
| sock
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class PyMongoProtocol(asyncio.protocols.BufferedProtocol)
| PyMongoProtocol(timeout: 'Optional[float]' = None)
|
| Method resolution order:
| PyMongoProtocol
| asyncio.protocols.BufferedProtocol
| asyncio.protocols.BaseProtocol
| builtins.object
|
| Methods defined here:
|
| __init__(self, timeout: 'Optional[float]' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| buffer_updated(self, nbytes: 'int') -> 'None'
| Called when the buffer was updated with the received data
|
| close(self, exc: 'Optional[Exception]' = None) -> 'None'
|
| connection_lost(self, exc: 'Optional[Exception]' = None) -> 'None'
| Called when the connection is lost or closed.
|
| The argument is an exception object or None (the latter
| meaning a regular EOF is received or the connection was
| aborted or closed).
|
| connection_made(self, transport: 'BaseTransport') -> 'None'
| Called exactly once when a connection is made.
| The transport argument is the transport representing the write side of the connection.
|
| get_buffer(self, sizehint: 'int') -> 'memoryview'
| Called to allocate a new receive buffer.
| The asyncio loop calls this method expecting to receive a non-empty buffer to fill with data.
| If any data does not fit into the returned buffer, this method will be called again until
| either no data remains or an empty buffer is returned.
|
| process_compression_header(self) -> 'tuple[int, int]'
| Unpack a MongoDB Wire Protocol compression header.
|
| process_header(self) -> 'tuple[int, int, int, bool]'
| Unpack a MongoDB Wire Protocol header.
|
| async read(self, request_id: 'Optional[int]', max_message_size: 'int') -> 'tuple[bytes, int]'
| Read a single MongoDB Wire Protocol message from this connection.
|
| settimeout(self, timeout: 'float | None') -> 'None'
|
| async wait_closed(self) -> 'None'
|
| async write(self, message: 'bytes') -> 'None'
| Write a message to this connection's transport.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| gettimeout
| The configured timeout for the socket that underlies our protocol pair.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from asyncio.protocols.BufferedProtocol:
|
| eof_received(self)
| Called when the other end calls write_eof() or equivalent.
|
| If this returns a false value (including None), the transport
| will close itself. If it returns a true value, closing the
| transport is up to the protocol.
|
| ----------------------------------------------------------------------
| Methods inherited from asyncio.protocols.BaseProtocol:
|
| pause_writing(self)
| Called when the transport's buffer goes over the high-water mark.
|
| Pause and resume calls are paired -- pause_writing() is called
| once when the buffer goes strictly over the high-water mark
| (even if subsequent writes increases the buffer size even
| more), and eventually resume_writing() is called once when the
| buffer size reaches the low-water mark.
|
| Note that if the buffer size equals the high-water mark,
| pause_writing() is not called -- it must go strictly over.
| Conversely, resume_writing() is called when the buffer size is
| equal or lower than the low-water mark. These end conditions
| are important to ensure that things go as expected when either
| mark is zero.
|
| NOTE: This is the only Protocol callback that is not called
| through EventLoop.call_soon() -- if it were, it would have no
| effect when it's most needed (when the app keeps writing
| without yielding until pause_writing() is called).
|
| resume_writing(self)
| Called when the transport's buffer drains below the low-water mark.
|
| See pause_writing() for details.
FUNCTIONS
async async_receive_data_socket(sock: 'Union[socket.socket, _sslConn]', length: 'int') -> 'memoryview'
async async_receive_message(conn: 'AsyncConnection', request_id: 'Optional[int]', max_message_size: 'int' = 48000000) -> 'Union[_OpReply, _OpMsg]'
Receive a raw BSON message or raise socket.error.
async async_sendall(conn: 'PyMongoProtocol', buf: 'bytes') -> 'None'
async async_socket_sendall(sock: 'Union[socket.socket, _sslConn]', buf: 'bytes') -> 'None'
# These socket-based I/O methods are for KMS requests and any other network operations that do not use
# the MongoDB wire protocol
receive_data(conn: 'Connection', length: 'int', deadline: 'Optional[float]') -> 'memoryview'
receive_message(conn: 'Connection', request_id: 'Optional[int]', max_message_size: 'int' = 48000000) -> 'Union[_OpReply, _OpMsg]'
Receive a raw BSON message or raise socket.error.
sendall(sock: 'Union[socket.socket, _sslConn]', buf: 'bytes') -> 'None'
wait_for_read(conn: 'Connection', deadline: 'Optional[float]') -> 'None'
Block until at least one byte is read, or a timeout, or a cancel.
DATA
BLOCKING_IO_ERRORS = (<class 'BlockingIOError'>, <class 'OpenSSL.SSL.W...
BLOCKING_IO_LOOKUP_ERROR = (<class 'OpenSSL.SSL.WantReadError'>, <clas...
BLOCKING_IO_READ_ERROR = (<class 'OpenSSL.SSL.WantReadError'>, <class ...
BLOCKING_IO_WRITE_ERROR = (<class 'OpenSSL.SSL.WantWriteError'>, <clas...
MAX_MESSAGE_SIZE = 48000000
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
TYPE_CHECKING = False
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\network_layer.py
pymongo.ocsp_cache
Python Library Documentation: module pymongo.ocsp_cache in pymongo
NAME
pymongo.ocsp_cache - Utilities for caching OCSP responses.
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
TYPE_CHECKING = False
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\ocsp_cache.py
pymongo.ocsp_support
Python Library Documentation: module pymongo.ocsp_support in pymongo
NAME
pymongo.ocsp_support - Support for requesting and verifying OCSP responses.
DATA
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
TYPE_CHECKING = False
Type = typing.Type
Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\ocsp_support.py
pymongo.operations
Python Library Documentation: module pymongo.operations in pymongo
NAME
pymongo.operations - Operation class definitions.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
IndexModel
SearchIndexModel
_DeleteOp(builtins.object)
DeleteMany
DeleteOne
_UpdateOp(builtins.object)
UpdateMany
UpdateOne
typing.Generic(builtins.object)
InsertOne
ReplaceOne
class DeleteMany(_DeleteOp)
| DeleteMany(filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents a delete_many operation.
|
| Method resolution order:
| DeleteMany
| _DeleteOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create a DeleteMany instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the documents to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param namespace: (optional) The namespace in which to delete documents.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _DeleteOp:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _DeleteOp:
|
| __hash__ = None
class DeleteOne(_DeleteOp)
| DeleteOne(filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents a delete_one operation.
|
| Method resolution order:
| DeleteOne
| _DeleteOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create a DeleteOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to delete.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.4 and above.
| :param namespace: (optional) The namespace in which to delete a document.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _DeleteOp:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _DeleteOp:
|
| __hash__ = None
class IndexModel(builtins.object)
| IndexModel(keys: '_IndexKeyHint', **kwargs: 'Any') -> 'None'
|
| Represents an index to create.
|
| Methods defined here:
|
| __init__(self, keys: '_IndexKeyHint', **kwargs: 'Any') -> 'None'
| Create an Index instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_indexes` and :meth:`~pymongo.collection.Collection.create_indexes`.
|
| Takes either a single key or a list containing (key, direction) pairs
| or keys. If no direction is given, :data:`~pymongo.ASCENDING` will
| be assumed.
| The key(s) must be an instance of :class:`str`, and the direction(s) must
| be one of (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
| :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOSPHERE`,
| :data:`~pymongo.HASHED`, :data:`~pymongo.TEXT`).
|
| Valid options include, but are not limited to:
|
| - `name`: custom name to use for this index - if none is
| given, a name will be generated.
| - `unique`: if ``True``, creates a uniqueness constraint on the index.
| - `background`: if ``True``, this index should be created in the
| background.
| - `sparse`: if ``True``, omit from the index any documents that lack
| the indexed field.
| - `bucketSize`: for use with geoHaystack indexes.
| Number of documents to group together within a certain proximity
| to a given longitude and latitude.
| - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
| index.
| - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
| collection. MongoDB will automatically delete documents from
| this collection after <int> seconds. The indexed field must
| be a UTC datetime or the data will not expire.
| - `partialFilterExpression`: A document that specifies a filter for
| a partial index.
| - `collation`: An instance of :class:`~pymongo.collation.Collation`
| that specifies the collation to use.
| - `wildcardProjection`: Allows users to include or exclude specific
| field paths from a `wildcard index`_ using the { "$**" : 1} key
| pattern. Requires MongoDB >= 4.2.
| - `hidden`: if ``True``, this index will be hidden from the query
| planner and will not be evaluated as part of query plan
| selection. Requires MongoDB >= 4.4.
|
| See the MongoDB documentation for a full list of supported options by
| server version.
|
| :param keys: a single key or a list containing (key, direction) pairs
| or keys specifying the index to create.
| :param kwargs: any additional index creation
| options (see the above list) should be passed as keyword
| arguments.
|
| .. versionchanged:: 3.11
| Added the ``hidden`` option.
| .. versionchanged:: 3.2
| Added the ``partialFilterExpression`` option to support partial
| indexes.
|
| .. _wildcard index: https://dochub.mongodb.org/core/index-wildcard/
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| document
| An index document suitable for passing to the createIndexes
| command.
class InsertOne(typing.Generic)
| InsertOne(document: '_DocumentType', namespace: 'Optional[str]' = None) -> 'None'
|
| Represents an insert_one operation.
|
| Method resolution order:
| InsertOne
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, document: '_DocumentType', namespace: 'Optional[str]' = None) -> 'None'
| Create an InsertOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param document: The document to insert. If the document is missing an
| _id field one will be added.
| :param namespace: (optional) The namespace in which to insert a document.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __hash__ = None
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ReplaceOne(typing.Generic)
| ReplaceOne(filter: 'Mapping[str, Any]', replacement: 'Union[_DocumentType, RawBSONDocument]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
|
| Represents a replace_one operation.
|
| Method resolution order:
| ReplaceOne
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, filter: 'Mapping[str, Any]', replacement: 'Union[_DocumentType, RawBSONDocument]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
| Create a ReplaceOne instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to replace.
| :param replacement: The new document.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
| :param namespace: (optional) The namespace in which to replace a document.
|
| .. versionchanged:: 4.10
| Added ``sort`` option.
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the ``hint`` option.
| .. versionchanged:: 3.5
| Added the ``collation`` option.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __hash__ = None
|
| __orig_bases__ = (typing.Generic[~_DocumentType],)
|
| __parameters__ = (~_DocumentType,)
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class SearchIndexModel(builtins.object)
| SearchIndexModel(definition: 'Mapping[str, Any]', name: 'Optional[str]' = None, type: 'Optional[str]' = None, **kwargs: 'Any') -> 'None'
|
| Represents a search index to create.
|
| Methods defined here:
|
| __init__(self, definition: 'Mapping[str, Any]', name: 'Optional[str]' = None, type: 'Optional[str]' = None, **kwargs: 'Any') -> 'None'
| Create a Search Index instance.
|
| For use with :meth:`~pymongo.collection.AsyncCollection.create_search_index` and :meth:`~pymongo.collection.AsyncCollection.create_search_indexes`.
|
| :param definition: The definition for this index.
| :param name: The name for this index, if present.
| :param type: The type for this index which defaults to "search". Alternative values include "vectorSearch".
| :param kwargs: Keyword arguments supplying any additional options.
|
| .. note:: Search indexes require a MongoDB server version 7.0+ Atlas cluster.
| .. versionadded:: 4.5
| .. versionchanged:: 4.7
| Added the type and kwargs arguments.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| document
| The document for this index.
class UpdateMany(_UpdateOp)
| UpdateMany(filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
|
| Represents an update_many operation.
|
| Method resolution order:
| UpdateMany
| _UpdateOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None) -> 'None'
| Create an UpdateMany instance.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the documents to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param namespace: (optional) The namespace in which to update documents.
|
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the `hint` option.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the `update`.
| .. versionchanged:: 3.6
| Added the `array_filters` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _UpdateOp:
|
| __eq__(self, other: 'object') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _UpdateOp:
|
| __hash__ = None
class UpdateOne(_UpdateOp)
| UpdateOne(filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
|
| Represents an update_one operation.
|
| Method resolution order:
| UpdateOne
| _UpdateOp
| builtins.object
|
| Methods defined here:
|
| __init__(self, filter: 'Mapping[str, Any]', update: 'Union[Mapping[str, Any], _Pipeline]', upsert: 'Optional[bool]' = None, collation: 'Optional[_CollationIn]' = None, array_filters: 'Optional[list[Mapping[str, Any]]]' = None, hint: 'Optional[_IndexKeyHint]' = None, namespace: 'Optional[str]' = None, sort: 'Optional[Mapping[str, Any]]' = None) -> 'None'
| Represents an update_one operation.
|
| For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`,
| :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.bulk_write` and :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| :param filter: A query that matches the document to update.
| :param update: The modifications to apply.
| :param upsert: If ``True``, perform an insert if no documents
| match the filter.
| :param collation: An instance of
| :class:`~pymongo.collation.Collation`.
| :param array_filters: A list of filters specifying which
| array elements an update should apply.
| :param hint: An index to use to support the query
| predicate specified either by its string name, or in the same
| format as passed to
| :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` or :meth:`~pymongo.collection.Collection.create_index` (e.g.
| ``[('field', ASCENDING)]``). This option is only supported on
| MongoDB 4.2 and above.
| :param namespace: The namespace in which to update a document.
| :param sort: Specify which document the operation updates if the query matches
| multiple documents. The first document matched by the sort order will be updated.
|
| .. versionchanged:: 4.10
| Added ``sort`` option.
| .. versionchanged:: 4.9
| Added the `namespace` option to support `MongoClient.bulk_write`.
| .. versionchanged:: 3.11
| Added the `hint` option.
| .. versionchanged:: 3.9
| Added the ability to accept a pipeline as the `update`.
| .. versionchanged:: 3.6
| Added the `array_filters` option.
| .. versionchanged:: 3.5
| Added the `collation` option.
|
| ----------------------------------------------------------------------
| Methods inherited from _UpdateOp:
|
| __eq__(self, other: 'object') -> 'bool'
| Return self==value.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _UpdateOp:
|
| __hash__ = None
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
Tuple = typing.Tuple
Deprecated alias to builtins.tuple.
Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\operations.py
pymongo.periodic_executor
Python Library Documentation: module pymongo.periodic_executor in pymongo
NAME
pymongo.periodic_executor - Run a target function on a background thread.
CLASSES
builtins.object
AsyncPeriodicExecutor
PeriodicExecutor
class AsyncPeriodicExecutor(builtins.object)
| AsyncPeriodicExecutor(interval: 'float', min_interval: 'float', target: 'Any', name: 'Optional[str]' = None)
|
| Methods defined here:
|
| __init__(self, interval: 'float', min_interval: 'float', target: 'Any', name: 'Optional[str]' = None)
| Run a target function periodically on a background task.
|
| If the target's return value is false, the executor stops.
|
| :param interval: Seconds between calls to `target`.
| :param min_interval: Minimum seconds between calls if `wake` is
| called very often.
| :param target: A function.
| :param name: A name to give the underlying task.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| close(self, dummy: 'Any' = None) -> 'None'
| Stop. To restart, call open().
|
| The dummy parameter allows an executor's close method to be a weakref
| callback; see monitor.py.
|
| async join(self, timeout: 'Optional[int]' = None) -> 'None'
|
| open(self) -> 'None'
| Start. Multiple calls have no effect.
|
| skip_sleep(self) -> 'None'
|
| update_interval(self, new_interval: 'int') -> 'None'
|
| wake(self) -> 'None'
| Execute the target function soon.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class PeriodicExecutor(builtins.object)
| PeriodicExecutor(interval: 'float', min_interval: 'float', target: 'Any', name: 'Optional[str]' = None)
|
| Methods defined here:
|
| __init__(self, interval: 'float', min_interval: 'float', target: 'Any', name: 'Optional[str]' = None)
| Run a target function periodically on a background thread.
|
| If the target's return value is false, the executor stops.
|
| :param interval: Seconds between calls to `target`.
| :param min_interval: Minimum seconds between calls if `wake` is
| called very often.
| :param target: A function.
| :param name: A name to give the underlying thread.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| close(self, dummy: 'Any' = None) -> 'None'
| Stop. To restart, call open().
|
| The dummy parameter allows an executor's close method to be a weakref
| callback; see monitor.py.
|
| join(self, timeout: 'Optional[int]' = None) -> 'None'
|
| open(self) -> 'None'
| Start. Multiple calls have no effect.
|
| Not safe to call from multiple threads at once.
|
| skip_sleep(self) -> 'None'
|
| update_interval(self, new_interval: 'int') -> 'None'
|
| wake(self) -> 'None'
| Execute the target function soon.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\periodic_executor.py
pymongo.pool_options
Python Library Documentation: module pymongo.pool_options in pymongo
NAME
pymongo.pool_options - Pool options for AsyncMongoClient/MongoClient.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
PoolOptions
class PoolOptions(builtins.object)
| PoolOptions(max_pool_size: 'int' = 100, min_pool_size: 'int' = 0, max_idle_time_seconds: 'Optional[int]' = None, connect_timeout: 'Optional[float]' = None, socket_timeout: 'Optional[float]' = None, wait_queue_timeout: 'Optional[int]' = None, ssl_context: 'Optional[SSLContext]' = None, tls_allow_invalid_hostnames: 'bool' = False, event_listeners: 'Optional[_EventListeners]' = None, appname: 'Optional[str]' = None, driver: 'Optional[DriverInfo]' = None, compression_settings: 'Optional[CompressionSettings]' = None, max_connecting: 'int' = 2, pause_enabled: 'bool' = True, server_api: 'Optional[ServerApi]' = None, load_balanced: 'Optional[bool]' = None, credentials: 'Optional[MongoCredential]' = None, is_sync: 'Optional[bool]' = True)
|
| Read only connection pool options for an AsyncMongoClient/MongoClient.
|
| Should not be instantiated directly by application developers. Access
| a client's pool options via
| :attr:`~pymongo.client_options.ClientOptions.pool_options` instead::
|
| pool_opts = client.options.pool_options
| pool_opts.max_pool_size
| pool_opts.min_pool_size
|
| Methods defined here:
|
| __init__(self, max_pool_size: 'int' = 100, min_pool_size: 'int' = 0, max_idle_time_seconds: 'Optional[int]' = None, connect_timeout: 'Optional[float]' = None, socket_timeout: 'Optional[float]' = None, wait_queue_timeout: 'Optional[int]' = None, ssl_context: 'Optional[SSLContext]' = None, tls_allow_invalid_hostnames: 'bool' = False, event_listeners: 'Optional[_EventListeners]' = None, appname: 'Optional[str]' = None, driver: 'Optional[DriverInfo]' = None, compression_settings: 'Optional[CompressionSettings]' = None, max_connecting: 'int' = 2, pause_enabled: 'bool' = True, server_api: 'Optional[ServerApi]' = None, load_balanced: 'Optional[bool]' = None, credentials: 'Optional[MongoCredential]' = None, is_sync: 'Optional[bool]' = True)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| appname
| The application name, for sending with hello in server handshake.
|
| connect_timeout
| How long a connection can take to be opened before timing out.
|
| driver
| Driver name and version, for sending with hello in handshake.
|
| load_balanced
| True if this Pool is configured in load balanced mode.
|
| max_connecting
| The maximum number of concurrent connection creation attempts per
| pool. Defaults to 2.
|
| max_idle_time_seconds
| The maximum number of seconds that a connection can remain
| idle in the pool before being removed and replaced. Defaults to
| `None` (no limit).
|
| 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
| :exc:`~pymongo.errors.ConnectionFailure` after a timeout.
| By default ``waitQueueTimeoutMS`` is not set.
|
| metadata
| A dict of metadata about the application, driver, os, and platform.
|
| min_pool_size
| The minimum required number of concurrent connections that the pool
| will maintain to each connected server. Default is 0.
|
| non_default_options
| The non-default options this pool was created with.
|
| Added for CMAP's :class:`PoolCreatedEvent`.
|
| pause_enabled
|
| server_api
| A pymongo.server_api.ServerApi or None.
|
| socket_timeout
| How long a send or receive on a socket can take before timing out.
|
| tls_allow_invalid_hostnames
| If True skip ssl.match_hostname.
|
| wait_queue_timeout
| How long a thread will wait for a socket from the pool if the pool
| has no free sockets.
FUNCTIONS
get_container_env_info() -> 'dict[str, str]'
Returns the runtime and orchestrator of a container.
If neither value is present, the metadata client.env.container field will be omitted.
DATA
DOCKER_ENV_PATH = '/.dockerenv'
ENV_VAR_K8S = 'KUBERNETES_SERVICE_HOST'
MAX_CONNECTING = 2
MAX_IDLE_TIME_SEC = None
MAX_POOL_SIZE = 100
MIN_POOL_SIZE = 0
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
ORCHESTRATOR_NAME_K8S = 'kubernetes'
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
RUNTIME_NAME_DOCKER = 'docker'
TYPE_CHECKING = False
WAIT_QUEUE_TIMEOUT = None
__annotations__ = {'_METADATA': 'dict[str, Any]'}
VERSION
4.17.0
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\pool_options.py
pymongo.pyopenssl_context
Python Library Documentation: module pymongo.pyopenssl_context in pymongo
NAME
pymongo.pyopenssl_context
DESCRIPTION
A CPython compatible SSLContext implementation wrapping PyOpenSSL's
context.
Due to limitations of the CPython asyncio.Protocol implementation for SSL, the async API does not support PyOpenSSL.
CLASSES
builtins.object
SSLContext
class SSLContext(builtins.object)
| SSLContext(protocol: 'int')
|
| A CPython compatible SSLContext implementation wrapping PyOpenSSL's
| context.
|
| Methods defined here:
|
| __init__(self, protocol: 'int')
| Initialize self. See help(type(self)) for accurate signature.
|
| load_cert_chain(self, certfile: 'Union[str, bytes]', keyfile: 'Union[str, bytes, None]' = None, password: 'Optional[str]' = None) -> 'None'
| Load a private key and the corresponding certificate. The certfile
| string must be the path to a single file in PEM format containing the
| certificate as well as any number of CA certificates needed to
| establish the certificate's authenticity. The keyfile string, if
| present, must point to a file containing the private key. Otherwise
| the private key will be taken from certfile as well.
|
| load_default_certs(self) -> 'None'
| A PyOpenSSL version of load_default_certs from CPython.
|
| load_verify_locations(self, cafile: 'Optional[str]' = None, capath: 'Optional[str]' = None) -> 'None'
| Load a set of "certification authority"(CA) certificates used to
| validate other peers' certificates when `~verify_mode` is other than
| ssl.CERT_NONE.
|
| set_default_verify_paths(self) -> 'None'
| Specify that the platform provided CA certificates are to be used
| for verification purposes.
|
| wrap_socket(self, sock: '_socket.socket', server_side: 'bool' = False, do_handshake_on_connect: 'bool' = True, suppress_ragged_eofs: 'bool' = True, server_hostname: 'Optional[str]' = None, session: 'Optional[_SSL.Session]' = None) -> '_sslConn'
| Wrap an existing Python socket connection and return a TLS socket
| object.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| protocol
| The protocol version chosen when constructing the context.
| This attribute is read-only.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| check_hostname
|
| check_ocsp_endpoint
|
| options
|
| verify_mode
| Whether to try to verify other peers' certificates and how to
| behave if verification fails. This attribute must be one of
| ssl.CERT_NONE, ssl.CERT_OPTIONAL or ssl.CERT_REQUIRED.
DATA
BLOCKING_IO_ERRORS = (<class 'OpenSSL.SSL.WantReadError'>, <class 'Ope...
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
HAS_SNI = True
IS_PYOPENSSL = True
OP_NO_COMPRESSION = 131072
OP_NO_RENEGOTIATION = 1073741824
OP_NO_SSLv2 = 0
OP_NO_SSLv3 = 33554432
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
PROTOCOL_SSLv23 = 3
TYPE_CHECKING = False
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\pyopenssl_context.py
pymongo.read_concern
Python Library Documentation: module pymongo.read_concern in pymongo
NAME
pymongo.read_concern - Tools for working with read concerns.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
ReadConcern
class ReadConcern(builtins.object)
| ReadConcern(level: 'Optional[str]' = None) -> 'None'
|
| ReadConcern
|
| :param level: (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.
|
| .. versionadded:: 3.2
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, level: 'Optional[str]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| document
| The document representation of this read concern.
|
| .. note::
| :class:`ReadConcern` is immutable. Mutating the value of
| :attr:`document` does not mutate this :class:`ReadConcern`.
|
| level
| The read concern level.
|
| ok_for_legacy
| Return ``True`` if this read concern is compatible with
| old wire protocol versions.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
DATA
DEFAULT_READ_CONCERN = ReadConcern()
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\read_concern.py
pymongo.read_preferences
Python Library Documentation: module pymongo.read_preferences in pymongo
NAME
pymongo.read_preferences - Utilities for choosing which member of a replica set to read from.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
MovingAverage
ReadPreference
_ServerMode(builtins.object)
Nearest
Primary
PrimaryPreferred
Secondary
SecondaryPreferred
class MovingAverage(builtins.object)
| MovingAverage() -> 'None'
|
| Tracks an exponentially-weighted moving average.
|
| Methods defined here:
|
| __init__(self) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| add_sample(self, sample: 'float') -> 'None'
|
| get(self) -> 'Optional[float]'
| Get the calculated average, or None if no samples yet.
|
| reset(self) -> 'None'
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'average': 'Optional[float]'}
class Nearest(_ServerMode)
| Nearest(tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
|
| Nearest read preference.
|
| * When directly connected to one mongod queries are allowed to standalone
| servers, to a replica set primary, or to replica set secondaries.
| * When connected to a mongos queries are distributed among all members of
| a shard.
| * When connected to a replica set queries are distributed among all
| members.
|
| :param tag_sets: The :attr:`~tag_sets` for this read preference.
| :param max_staleness: (integer, in seconds) 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.
| Default -1, meaning no maximum. If it is set, it must be at least
| 90 seconds.
| :param hedge: **DEPRECATED** - The :attr:`~hedge` for this read preference.
|
| .. versionchanged:: 3.11
| Added ``hedge`` parameter.
|
| Method resolution order:
| Nearest
| _ServerMode
| builtins.object
|
| Methods defined here:
|
| __call__(self, selection: 'Selection') -> 'Selection'
| Apply this read preference to Selection.
|
| __init__(self, tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from _ServerMode:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getstate__(self) -> 'dict[str, Any]'
| Return value of object for pickling.
|
| Needed explicitly because __slots__() defined.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __setstate__(self, value: 'Mapping[str, Any]') -> 'None'
| Restore from pickling.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerMode:
|
| document
| Read preference as a document.
|
| hedge
| **DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0.
|
| The read preference ``hedge`` parameter.
|
| A dictionary that configures how the server will perform hedged reads.
| It consists of the following keys:
|
| - ``enabled``: Enables or disables hedged reads in sharded clusters.
|
| Hedged reads are automatically enabled in MongoDB 4.4+ when using a
| ``nearest`` read preference. To explicitly enable hedged reads, set
| the ``enabled`` key to ``true``::
|
| >>> Nearest(hedge={'enabled': True})
|
| To explicitly disable hedged reads, set the ``enabled`` key to
| ``False``::
|
| >>> Nearest(hedge={'enabled': False})
|
| .. versionadded:: 3.11
|
| max_staleness
| The maximum estimated length of time (in seconds) a replica set
| secondary can fall behind the primary in replication before it will
| no longer be selected for operations, or -1 for no maximum.
|
| min_wire_version
| The wire protocol version the server must support.
|
| Some read preferences impose version requirements on all servers (e.g.
| maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).
|
| All servers' maxWireVersion must be at least this read preference's
| `min_wire_version`, or the driver raises
| :exc:`~pymongo.errors.ConfigurationError`.
|
| mode
| The mode of this read preference instance.
|
| mongos_mode
| The mongos mode of this read preference.
|
| name
| The name of this read preference.
|
| 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." MongoClient tries each set of tags in turn
| until it finds a set of tags with at least one matching member.
| For example, to only send a query to an analytic node::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| Or using :class:`SecondaryPreferred`::
|
| SecondaryPreferred(tag_sets=[{"node":"analytics"}])
|
| .. seealso:: `Data-Center Awareness
| <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _ServerMode:
|
| __hash__ = None
class Primary(_ServerMode)
| Primary() -> 'None'
|
| Primary read preference.
|
| * When directly connected to one mongod queries are allowed if the server
| is standalone or a replica set primary.
| * When connected to a mongos queries are sent to the primary of a shard.
| * When connected to a replica set queries are sent to the primary of
| the replica set.
|
| Method resolution order:
| Primary
| _ServerMode
| builtins.object
|
| Methods defined here:
|
| __call__(self, selection: 'Selection') -> 'Selection'
| Apply this read preference to a Selection.
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from _ServerMode:
|
| __getstate__(self) -> 'dict[str, Any]'
| Return value of object for pickling.
|
| Needed explicitly because __slots__() defined.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __setstate__(self, value: 'Mapping[str, Any]') -> 'None'
| Restore from pickling.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerMode:
|
| document
| Read preference as a document.
|
| hedge
| **DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0.
|
| The read preference ``hedge`` parameter.
|
| A dictionary that configures how the server will perform hedged reads.
| It consists of the following keys:
|
| - ``enabled``: Enables or disables hedged reads in sharded clusters.
|
| Hedged reads are automatically enabled in MongoDB 4.4+ when using a
| ``nearest`` read preference. To explicitly enable hedged reads, set
| the ``enabled`` key to ``true``::
|
| >>> Nearest(hedge={'enabled': True})
|
| To explicitly disable hedged reads, set the ``enabled`` key to
| ``False``::
|
| >>> Nearest(hedge={'enabled': False})
|
| .. versionadded:: 3.11
|
| max_staleness
| The maximum estimated length of time (in seconds) a replica set
| secondary can fall behind the primary in replication before it will
| no longer be selected for operations, or -1 for no maximum.
|
| min_wire_version
| The wire protocol version the server must support.
|
| Some read preferences impose version requirements on all servers (e.g.
| maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).
|
| All servers' maxWireVersion must be at least this read preference's
| `min_wire_version`, or the driver raises
| :exc:`~pymongo.errors.ConfigurationError`.
|
| mode
| The mode of this read preference instance.
|
| mongos_mode
| The mongos mode of this read preference.
|
| name
| The name of this read preference.
|
| 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." MongoClient tries each set of tags in turn
| until it finds a set of tags with at least one matching member.
| For example, to only send a query to an analytic node::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| Or using :class:`SecondaryPreferred`::
|
| SecondaryPreferred(tag_sets=[{"node":"analytics"}])
|
| .. seealso:: `Data-Center Awareness
| <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
class PrimaryPreferred(_ServerMode)
| PrimaryPreferred(tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
|
| PrimaryPreferred read preference.
|
| * When directly connected to one mongod queries are allowed to standalone
| servers, to a replica set primary, or to replica set secondaries.
| * When connected to a mongos queries are sent to the primary of a shard if
| available, otherwise a shard secondary.
| * When connected to a replica set queries are sent to the primary if
| available, otherwise a secondary.
|
| .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
| created reads will be routed to an available secondary until the
| primary of the replica set is discovered.
|
| :param tag_sets: The :attr:`~tag_sets` to use if the primary is not
| available.
| :param max_staleness: (integer, in seconds) 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.
| Default -1, meaning no maximum. If it is set, it must be at least
| 90 seconds.
| :param hedge: **DEPRECATED** - The :attr:`~hedge` for this read preference.
|
| .. versionchanged:: 3.11
| Added ``hedge`` parameter.
|
| Method resolution order:
| PrimaryPreferred
| _ServerMode
| builtins.object
|
| Methods defined here:
|
| __call__(self, selection: 'Selection') -> 'Selection'
| Apply this read preference to Selection.
|
| __init__(self, tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from _ServerMode:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getstate__(self) -> 'dict[str, Any]'
| Return value of object for pickling.
|
| Needed explicitly because __slots__() defined.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __setstate__(self, value: 'Mapping[str, Any]') -> 'None'
| Restore from pickling.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerMode:
|
| document
| Read preference as a document.
|
| hedge
| **DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0.
|
| The read preference ``hedge`` parameter.
|
| A dictionary that configures how the server will perform hedged reads.
| It consists of the following keys:
|
| - ``enabled``: Enables or disables hedged reads in sharded clusters.
|
| Hedged reads are automatically enabled in MongoDB 4.4+ when using a
| ``nearest`` read preference. To explicitly enable hedged reads, set
| the ``enabled`` key to ``true``::
|
| >>> Nearest(hedge={'enabled': True})
|
| To explicitly disable hedged reads, set the ``enabled`` key to
| ``False``::
|
| >>> Nearest(hedge={'enabled': False})
|
| .. versionadded:: 3.11
|
| max_staleness
| The maximum estimated length of time (in seconds) a replica set
| secondary can fall behind the primary in replication before it will
| no longer be selected for operations, or -1 for no maximum.
|
| min_wire_version
| The wire protocol version the server must support.
|
| Some read preferences impose version requirements on all servers (e.g.
| maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).
|
| All servers' maxWireVersion must be at least this read preference's
| `min_wire_version`, or the driver raises
| :exc:`~pymongo.errors.ConfigurationError`.
|
| mode
| The mode of this read preference instance.
|
| mongos_mode
| The mongos mode of this read preference.
|
| name
| The name of this read preference.
|
| 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." MongoClient tries each set of tags in turn
| until it finds a set of tags with at least one matching member.
| For example, to only send a query to an analytic node::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| Or using :class:`SecondaryPreferred`::
|
| SecondaryPreferred(tag_sets=[{"node":"analytics"}])
|
| .. seealso:: `Data-Center Awareness
| <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _ServerMode:
|
| __hash__ = None
class ReadPreference(builtins.object)
| An enum that defines some commonly used read preference modes.
|
| Apps can also create a custom read preference, for example::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| See `Read and Write Settings <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/configure/#read-and-write-settings>`_ for code examples.
|
| A read preference is used in three cases:
|
| :class:`~pymongo.mongo_client.MongoClient` connected to a single mongod:
|
| - ``PRIMARY``: Queries are allowed if the server is standalone or a replica
| set primary.
| - All other modes allow queries to standalone servers, to a replica set
| primary, or to replica set secondaries.
|
| :class:`~pymongo.mongo_client.MongoClient` initialized with the
| ``replicaSet`` option:
|
| - ``PRIMARY``: Read from the primary. This is the default, and provides the
| strongest consistency. If no primary is available, raise
| :class:`~pymongo.errors.AutoReconnect`.
|
| - ``PRIMARY_PREFERRED``: Read from the primary if available, or if there is
| none, read from a secondary.
|
| - ``SECONDARY``: Read from a secondary. If no secondary is available,
| raise :class:`~pymongo.errors.AutoReconnect`.
|
| - ``SECONDARY_PREFERRED``: Read from a secondary if available, otherwise
| from the primary.
|
| - ``NEAREST``: Read from any member.
|
| :class:`~pymongo.mongo_client.MongoClient` connected to a mongos, with a
| sharded cluster of replica sets:
|
| - ``PRIMARY``: Read from the primary of the shard, or raise
| :class:`~pymongo.errors.OperationFailure` if there is none.
| This is the default.
|
| - ``PRIMARY_PREFERRED``: Read from the primary of the shard, or if there is
| none, read from a secondary of the shard.
|
| - ``SECONDARY``: Read from a secondary of the shard, or raise
| :class:`~pymongo.errors.OperationFailure` if there is none.
|
| - ``SECONDARY_PREFERRED``: Read from a secondary of the shard if available,
| otherwise from the shard primary.
|
| - ``NEAREST``: Read from any shard member.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| NEAREST = Nearest(tag_sets=None, max_staleness=-1, hedge=None)
|
| PRIMARY = Primary()
|
| PRIMARY_PREFERRED = PrimaryPreferred(tag_sets=None, max_staleness=-1, ...
|
| SECONDARY = Secondary(tag_sets=None, max_staleness=-1, hedge=None)
|
| SECONDARY_PREFERRED = SecondaryPreferred(tag_sets=None, max_staleness=...
class Secondary(_ServerMode)
| Secondary(tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
|
| Secondary read preference.
|
| * When directly connected to one mongod queries are allowed to standalone
| servers, to a replica set primary, or to replica set secondaries.
| * When connected to a mongos queries are distributed among shard
| secondaries. An error is raised if no secondaries are available.
| * When connected to a replica set queries are distributed among
| secondaries. An error is raised if no secondaries are available.
|
| :param tag_sets: The :attr:`~tag_sets` for this read preference.
| :param max_staleness: (integer, in seconds) 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.
| Default -1, meaning no maximum. If it is set, it must be at least
| 90 seconds.
| :param hedge: **DEPRECATED** - The :attr:`~hedge` for this read preference.
|
| .. versionchanged:: 3.11
| Added ``hedge`` parameter.
|
| Method resolution order:
| Secondary
| _ServerMode
| builtins.object
|
| Methods defined here:
|
| __call__(self, selection: 'Selection') -> 'Selection'
| Apply this read preference to Selection.
|
| __init__(self, tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from _ServerMode:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getstate__(self) -> 'dict[str, Any]'
| Return value of object for pickling.
|
| Needed explicitly because __slots__() defined.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __setstate__(self, value: 'Mapping[str, Any]') -> 'None'
| Restore from pickling.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerMode:
|
| document
| Read preference as a document.
|
| hedge
| **DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0.
|
| The read preference ``hedge`` parameter.
|
| A dictionary that configures how the server will perform hedged reads.
| It consists of the following keys:
|
| - ``enabled``: Enables or disables hedged reads in sharded clusters.
|
| Hedged reads are automatically enabled in MongoDB 4.4+ when using a
| ``nearest`` read preference. To explicitly enable hedged reads, set
| the ``enabled`` key to ``true``::
|
| >>> Nearest(hedge={'enabled': True})
|
| To explicitly disable hedged reads, set the ``enabled`` key to
| ``False``::
|
| >>> Nearest(hedge={'enabled': False})
|
| .. versionadded:: 3.11
|
| max_staleness
| The maximum estimated length of time (in seconds) a replica set
| secondary can fall behind the primary in replication before it will
| no longer be selected for operations, or -1 for no maximum.
|
| min_wire_version
| The wire protocol version the server must support.
|
| Some read preferences impose version requirements on all servers (e.g.
| maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).
|
| All servers' maxWireVersion must be at least this read preference's
| `min_wire_version`, or the driver raises
| :exc:`~pymongo.errors.ConfigurationError`.
|
| mode
| The mode of this read preference instance.
|
| mongos_mode
| The mongos mode of this read preference.
|
| name
| The name of this read preference.
|
| 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." MongoClient tries each set of tags in turn
| until it finds a set of tags with at least one matching member.
| For example, to only send a query to an analytic node::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| Or using :class:`SecondaryPreferred`::
|
| SecondaryPreferred(tag_sets=[{"node":"analytics"}])
|
| .. seealso:: `Data-Center Awareness
| <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _ServerMode:
|
| __hash__ = None
class SecondaryPreferred(_ServerMode)
| SecondaryPreferred(tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
|
| SecondaryPreferred read preference.
|
| * When directly connected to one mongod queries are allowed to standalone
| servers, to a replica set primary, or to replica set secondaries.
| * When connected to a mongos queries are distributed among shard
| secondaries, or the shard primary if no secondary is available.
| * When connected to a replica set queries are distributed among
| secondaries, or the primary if no secondary is available.
|
| .. note:: When a :class:`~pymongo.mongo_client.MongoClient` is first
| created reads will be routed to the primary of the replica set until
| an available secondary is discovered.
|
| :param tag_sets: The :attr:`~tag_sets` for this read preference.
| :param max_staleness: (integer, in seconds) 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.
| Default -1, meaning no maximum. If it is set, it must be at least
| 90 seconds.
| :param hedge: **DEPRECATED** - The :attr:`~hedge` for this read preference.
|
| .. versionchanged:: 3.11
| Added ``hedge`` parameter.
|
| Method resolution order:
| SecondaryPreferred
| _ServerMode
| builtins.object
|
| Methods defined here:
|
| __call__(self, selection: 'Selection') -> 'Selection'
| Apply this read preference to Selection.
|
| __init__(self, tag_sets: 'Optional[_TagSets]' = None, max_staleness: 'int' = -1, hedge: 'Optional[_Hedge]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from _ServerMode:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getstate__(self) -> 'dict[str, Any]'
| Return value of object for pickling.
|
| Needed explicitly because __slots__() defined.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __setstate__(self, value: 'Mapping[str, Any]') -> 'None'
| Restore from pickling.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _ServerMode:
|
| document
| Read preference as a document.
|
| hedge
| **DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0.
|
| The read preference ``hedge`` parameter.
|
| A dictionary that configures how the server will perform hedged reads.
| It consists of the following keys:
|
| - ``enabled``: Enables or disables hedged reads in sharded clusters.
|
| Hedged reads are automatically enabled in MongoDB 4.4+ when using a
| ``nearest`` read preference. To explicitly enable hedged reads, set
| the ``enabled`` key to ``true``::
|
| >>> Nearest(hedge={'enabled': True})
|
| To explicitly disable hedged reads, set the ``enabled`` key to
| ``False``::
|
| >>> Nearest(hedge={'enabled': False})
|
| .. versionadded:: 3.11
|
| max_staleness
| The maximum estimated length of time (in seconds) a replica set
| secondary can fall behind the primary in replication before it will
| no longer be selected for operations, or -1 for no maximum.
|
| min_wire_version
| The wire protocol version the server must support.
|
| Some read preferences impose version requirements on all servers (e.g.
| maxStalenessSeconds requires MongoDB 3.4 / maxWireVersion 5).
|
| All servers' maxWireVersion must be at least this read preference's
| `min_wire_version`, or the driver raises
| :exc:`~pymongo.errors.ConfigurationError`.
|
| mode
| The mode of this read preference instance.
|
| mongos_mode
| The mongos mode of this read preference.
|
| name
| The name of this read preference.
|
| 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." MongoClient tries each set of tags in turn
| until it finds a set of tags with at least one matching member.
| For example, to only send a query to an analytic node::
|
| Nearest(tag_sets=[{"node":"analytics"}])
|
| Or using :class:`SecondaryPreferred`::
|
| SecondaryPreferred(tag_sets=[{"node":"analytics"}])
|
| .. seealso:: `Data-Center Awareness
| <https://www.mongodb.com/docs/manual/data-center-awareness/>`_
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from _ServerMode:
|
| __hash__ = None
FUNCTIONS
make_read_preference(mode: 'int', tag_sets: 'Optional[_TagSets]', max_staleness: 'int' = -1) -> '_ServerMode'
read_pref_mode_from_name(name: 'str') -> 'int'
Get the read preference mode from mongos/uri name.
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\read_preferences.py
pymongo.response
Python Library Documentation: module pymongo.response in pymongo
NAME
pymongo.response - Represent a response from the server.
CLASSES
builtins.object
Response
PinnedResponse
class PinnedResponse(Response)
| PinnedResponse(data: 'Union[_OpMsg, _OpReply]', address: '_Address', conn: '_AgnosticConnection', request_id: 'int', duration: 'Optional[timedelta]', from_command: 'bool', docs: 'list[_DocumentOut]', more_to_come: 'bool')
|
| Method resolution order:
| PinnedResponse
| Response
| builtins.object
|
| Methods defined here:
|
| __init__(self, data: 'Union[_OpMsg, _OpReply]', address: '_Address', conn: '_AgnosticConnection', request_id: 'int', duration: 'Optional[timedelta]', from_command: 'bool', docs: 'list[_DocumentOut]', more_to_come: 'bool')
| Represent a response to an exhaust cursor's initial query.
|
| :param data: A network response message.
| :param address: (host, port) of the source server.
| :param conn: The AsyncConnection/Connection used for the initial query.
| :param request_id: The request id of this operation.
| :param duration: The duration of the operation.
| :param from_command: If the response is the result of a db command.
| :param docs: List of documents.
| :param more_to_come: Bool indicating whether cursor is ready to be
| exhausted.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| conn
| The AsyncConnection/Connection used for the initial query.
|
| The server will send batches on this socket, without waiting for
| getMores from the client, until the result set is exhausted or there
| is an error.
|
| more_to_come
| If true, server is ready to send batches on the socket until the
| result set is exhausted or there is an error.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Response:
|
| address
| (host, port) of the source server.
|
| data
| Server response's raw BSON bytes.
|
| docs
| The decoded document(s).
|
| duration
| The duration of the operation.
|
| from_command
| If the response is a result from a db command.
|
| request_id
| The request id of this operation.
class Response(builtins.object)
| Response(data: 'Union[_OpMsg, _OpReply]', address: '_Address', request_id: 'int', duration: 'Optional[timedelta]', from_command: 'bool', docs: 'Sequence[Mapping[str, Any]]')
|
| Methods defined here:
|
| __init__(self, data: 'Union[_OpMsg, _OpReply]', address: '_Address', request_id: 'int', duration: 'Optional[timedelta]', from_command: 'bool', docs: 'Sequence[Mapping[str, Any]]')
| Represent a response from the server.
|
| :param data: A network response message.
| :param address: (host, port) of the source server.
| :param request_id: The request id of this operation.
| :param duration: The duration of the operation.
| :param from_command: if the response is the result of a db command.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| address
| (host, port) of the source server.
|
| data
| Server response's raw BSON bytes.
|
| docs
| The decoded document(s).
|
| duration
| The duration of the operation.
|
| from_command
| If the response is a result from a db command.
|
| request_id
| The request id of this operation.
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
TYPE_CHECKING = False
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\response.py
pymongo.results
Python Library Documentation: module pymongo.results in pymongo
NAME
pymongo.results - Result class definitions.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
_BulkWriteResultBase(_WriteResult)
BulkWriteResult
ClientBulkWriteResult
_WriteResult(builtins.object)
DeleteResult
InsertManyResult
InsertOneResult
UpdateResult
class BulkWriteResult(_BulkWriteResultBase)
| BulkWriteResult(bulk_api_result: 'dict[str, Any]', acknowledged: 'bool') -> 'None'
|
| An object wrapper for collection-level bulk write API results.
|
| Method resolution order:
| BulkWriteResult
| _BulkWriteResultBase
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, bulk_api_result: 'dict[str, Any]', acknowledged: 'bool') -> 'None'
| Create a BulkWriteResult instance.
|
| :param bulk_api_result: A result dict from the collection-level bulk write API
| :param acknowledged: Was this write result acknowledged? If ``False``
| then all properties of this object will raise
| :exc:`~pymongo.errors.InvalidOperation`.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| upserted_ids
| A map of operation index to the _id of the upserted document.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _BulkWriteResultBase:
|
| bulk_api_result
| The raw bulk write API result.
|
| deleted_count
| The number of documents deleted.
|
| inserted_count
| The number of documents inserted.
|
| matched_count
| The number of documents matched for an update.
|
| modified_count
| The number of documents modified.
|
| upserted_count
| The number of documents upserted.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
class ClientBulkWriteResult(_BulkWriteResultBase)
| ClientBulkWriteResult(bulk_api_result: 'MutableMapping[str, Any]', acknowledged: 'bool', has_verbose_results: 'bool') -> 'None'
|
| An object wrapper for client-level bulk write API results.
|
| Method resolution order:
| ClientBulkWriteResult
| _BulkWriteResultBase
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, bulk_api_result: 'MutableMapping[str, Any]', acknowledged: 'bool', has_verbose_results: 'bool') -> 'None'
| Create a ClientBulkWriteResult instance.
|
| :param bulk_api_result: A result dict from the client-level bulk write API
| :param acknowledged: Was this write result acknowledged? If ``False``
| then all properties of this object will raise
| :exc:`~pymongo.errors.InvalidOperation`.
| :param has_verbose_results: Should the returned result be verbose?
| If ``False``, then the ``insert_results``, ``update_results``, and
| ``delete_results`` properties of this object will raise
| :exc:`~pymongo.errors.InvalidOperation`.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| delete_results
| A map of successful delete operations to their results.
|
| has_verbose_results
| Whether the returned results should be verbose.
|
| insert_results
| A map of successful insertion operations to their results.
|
| update_results
| A map of successful update operations to their results.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _BulkWriteResultBase:
|
| bulk_api_result
| The raw bulk write API result.
|
| deleted_count
| The number of documents deleted.
|
| inserted_count
| The number of documents inserted.
|
| matched_count
| The number of documents matched for an update.
|
| modified_count
| The number of documents modified.
|
| upserted_count
| The number of documents upserted.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
class DeleteResult(_WriteResult)
| DeleteResult(raw_result: 'Mapping[str, Any]', acknowledged: 'bool') -> 'None'
|
| The return type for :meth:`~pymongo.collection.Collection.delete_one`
| and :meth:`~pymongo.collection.Collection.delete_many`
| and as part of :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| Method resolution order:
| DeleteResult
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, raw_result: 'Mapping[str, Any]', acknowledged: 'bool') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| deleted_count
| The number of documents deleted.
|
| raw_result
| The raw result document returned by the server.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
class InsertManyResult(_WriteResult)
| InsertManyResult(inserted_ids: 'list[Any]', acknowledged: 'bool') -> 'None'
|
| The return type for :meth:`~pymongo.collection.Collection.insert_many`.
|
| Method resolution order:
| InsertManyResult
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, inserted_ids: 'list[Any]', acknowledged: 'bool') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inserted_ids
| A list of _ids of the inserted documents, in the order provided.
|
| .. note:: If ``False`` is passed for the `ordered` parameter to
| :meth:`~pymongo.collection.Collection.insert_many` the server
| may have inserted the documents in a different order than what
| is presented here.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
class InsertOneResult(_WriteResult)
| InsertOneResult(inserted_id: 'Any', acknowledged: 'bool') -> 'None'
|
| The return type for :meth:`~pymongo.collection.Collection.insert_one`
| and as part of :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| Method resolution order:
| InsertOneResult
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, inserted_id: 'Any', acknowledged: 'bool') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| inserted_id
| The inserted document's _id.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
class UpdateResult(_WriteResult)
| UpdateResult(raw_result: 'Optional[Mapping[str, Any]]', acknowledged: 'bool', in_client_bulk: 'bool' = False)
|
| The return type for :meth:`~pymongo.collection.Collection.update_one`,
| :meth:`~pymongo.collection.Collection.update_many`, and
| :meth:`~pymongo.collection.Collection.replace_one`, and as part of
| :meth:`~pymongo.mongo_client.MongoClient.bulk_write`.
|
| Method resolution order:
| UpdateResult
| _WriteResult
| builtins.object
|
| Methods defined here:
|
| __init__(self, raw_result: 'Optional[Mapping[str, Any]]', acknowledged: 'bool', in_client_bulk: 'bool' = False)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| did_upsert
| Whether an upsert took place.
|
| .. versionadded:: 4.9
|
| matched_count
| The number of documents matched for this update.
|
| modified_count
| The number of documents modified.
|
| raw_result
| The raw result document returned by the server.
|
| upserted_id
| The _id of the inserted document if an upsert took place. Otherwise
| ``None``.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from _WriteResult:
|
| acknowledged
| Is this the result of an acknowledged write operation?
|
| The :attr:`acknowledged` attribute will be ``False`` when using
| ``WriteConcern(w=0)``, otherwise ``True``.
|
| .. note::
| If the :attr:`acknowledged` attribute is ``False`` all other
| attributes of this class will raise
| :class:`~pymongo.errors.InvalidOperation` when accessed. Values for
| other attributes cannot be determined if the write operation was
| unacknowledged.
|
| .. seealso::
| :class:`~pymongo.write_concern.WriteConcern`
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\results.py
pymongo.server_api
Python Library Documentation: module pymongo.server_api in pymongo
NAME
pymongo.server_api - Support for MongoDB Stable API.
DESCRIPTION
.. _versioned-api-ref:
MongoDB Stable API
=====================
Starting in MongoDB 5.0, applications can specify the server API version
to use when creating a :class:`~pymongo.mongo_client.MongoClient`. Doing so
ensures that the driver behaves in a manner compatible with that server API
version, regardless of the server's actual release version.
Declaring an API Version
````````````````````````
.. attention:: Stable API requires MongoDB >=5.0.
To configure MongoDB Stable API, pass the ``server_api`` keyword option to
:class:`~pymongo.mongo_client.MongoClient`::
>>> from pymongo.mongo_client import MongoClient
>>> from pymongo.server_api import ServerApi
>>>
>>> # Declare API version "1" for MongoClient "client"
>>> server_api = ServerApi('1')
>>> client = MongoClient(server_api=server_api)
The declared API version is applied to all commands run through ``client``,
including those sent through the generic
:meth:`~pymongo.database.Database.command` helper.
.. note:: Declaring an API version on the
:class:`~pymongo.mongo_client.MongoClient` **and** specifying stable
API options in :meth:`~pymongo.database.Database.command` command document
is not supported and will lead to undefined behaviour.
To run any command without declaring a server API version or using a different
API version, create a separate :class:`~pymongo.mongo_client.MongoClient`
instance.
Strict Mode
```````````
Configuring ``strict`` mode will cause the MongoDB server to reject all
commands that are not part of the declared :attr:`ServerApi.version`. This
includes command options and aggregation pipeline stages.
For example::
>>> server_api = ServerApi('1', strict=True)
>>> client = MongoClient(server_api=server_api)
>>> client.test.command('count', 'test')
Traceback (most recent call last):
...
pymongo.errors.OperationFailure: Provided apiStrict:true, but the command count is not in API Version 1, full error: {'ok': 0.0, 'errmsg': 'Provided apiStrict:true, but the command count is not in API Version 1', 'code': 323, 'codeName': 'APIStrictError'
Detecting API Deprecations
``````````````````````````
The ``deprecationErrors`` option can be used to enable command failures
when using functionality that is deprecated from the configured
:attr:`ServerApi.version`. For example::
>>> server_api = ServerApi('1', deprecation_errors=True)
>>> client = MongoClient(server_api=server_api)
Note that at the time of this writing, no deprecated APIs exist.
Classes
=======
CLASSES
builtins.object
ServerApi
ServerApiVersion
class ServerApi(builtins.object)
| ServerApi(version: 'str', strict: 'Optional[bool]' = None, deprecation_errors: 'Optional[bool]' = None)
|
| MongoDB Stable API.
|
| Methods defined here:
|
| __init__(self, version: 'str', strict: 'Optional[bool]' = None, deprecation_errors: 'Optional[bool]' = None)
| Options to configure MongoDB Stable API.
|
| :param version: The API version string. Must be one of the values in
| :class:`ServerApiVersion`.
| :param strict: Set to ``True`` to enable API strict mode.
| Defaults to ``None`` which means "use the server's default".
| :param deprecation_errors: Set to ``True`` to enable
| deprecation errors. Defaults to ``None`` which means "use the
| server's default".
|
| .. versionadded:: 3.12
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| deprecation_errors
| The API deprecation errors setting.
|
| When set, this value is sent to the server in the
| "apiDeprecationErrors" field.
|
| strict
| The API strict mode setting.
|
| When set, this value is sent to the server in the "apiStrict" field.
|
| version
| The API version setting.
|
| This value is sent to the server in the "apiVersion" field.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ServerApiVersion(builtins.object)
| An enum that defines values for :attr:`ServerApi.version`.
|
| .. versionadded:: 3.12
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| V1 = '1'
DATA
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\server_api.py
pymongo.server_description
Python Library Documentation: module pymongo.server_description in pymongo
NAME
pymongo.server_description - Represent one server the driver is connected to.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
ServerDescription
class ServerDescription(builtins.object)
| ServerDescription(address: '_Address', hello: 'Optional[Hello[dict[str, Any]]]' = None, round_trip_time: 'Optional[float]' = None, error: 'Optional[Exception]' = None, min_round_trip_time: 'float' = 0.0) -> 'None'
|
| Immutable representation of one server.
|
| :param address: A (host, port) pair
| :param hello: Optional Hello instance
| :param round_trip_time: Optional float
| :param error: Optional, the last error attempting to connect to the server
| :param round_trip_time: Optional float, the min latency from the most recent samples
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, address: '_Address', hello: 'Optional[Hello[dict[str, Any]]]' = None, round_trip_time: 'Optional[float]' = None, error: 'Optional[Exception]' = None, min_round_trip_time: 'float' = 0.0) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| to_unknown(self, error: 'Optional[Exception]' = None) -> 'ServerDescription'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| address
| The address (host, port) of this server.
|
| all_hosts
| List of hosts, passives, and arbiters known to this server.
|
| cluster_time
|
| election_id
|
| election_tuple
|
| error
| The last error attempting to connect to the server, or None.
|
| is_readable
|
| is_server_type_known
|
| is_writable
|
| last_update_time
|
| last_write_date
|
| logical_session_timeout_minutes
|
| max_bson_size
|
| max_message_size
|
| max_wire_version
|
| max_write_batch_size
|
| me
|
| min_round_trip_time
| The min latency from the most recent samples.
|
| min_wire_version
|
| mongos
|
| primary
| This server's opinion about who the primary is, or None.
|
| replica_set_name
| Replica set name or None.
|
| retryable_reads_supported
| Checks if this server supports retryable writes.
|
| retryable_writes_supported
| Checks if this server supports retryable writes.
|
| round_trip_time
| The current average latency or None.
|
| server_type
| The type of this server.
|
| server_type_name
| The server type as a human readable string.
|
| .. versionadded:: 3.4
|
| set_version
|
| tags
|
| topology_version
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_host_to_round_trip_time': 'dict'}
|
| __hash__ = None
DATA
ClusterTime = typing.Mapping[str, typing.Any]
EPOCH_NAIVE = datetime.datetime(1970, 1, 1, 0, 0)
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\server_description.py
pymongo.server_selectors
Python Library Documentation: module pymongo.server_selectors in pymongo
NAME
pymongo.server_selectors - Criteria to select some ServerDescriptions from a TopologyDescription.
CLASSES
builtins.object
Selection
class Selection(builtins.object)
| Selection(topology_description: 'TopologyDescription', server_descriptions: 'list[ServerDescription]', common_wire_version: 'Optional[int]', primary: 'Optional[ServerDescription]')
|
| Input or output of a server selector function.
|
| Methods defined here:
|
| __bool__(self) -> 'bool'
|
| __getitem__(self, item: 'int') -> 'ServerDescription'
|
| __init__(self, topology_description: 'TopologyDescription', server_descriptions: 'list[ServerDescription]', common_wire_version: 'Optional[int]', primary: 'Optional[ServerDescription]')
| Initialize self. See help(type(self)) for accurate signature.
|
| secondary_with_max_last_write_date(self) -> 'Optional[ServerDescription]'
|
| with_server_descriptions(self, server_descriptions: 'list[ServerDescription]') -> 'Selection'
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_topology_description(topology_description: 'TopologyDescription') -> 'Selection'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| heartbeat_frequency
|
| primary_selection
|
| topology_type
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
any_server_selector(selection: 'T') -> 'T'
apply_single_tag_set(tag_set: 'TagSet', selection: 'Selection') -> 'Selection'
All servers matching one tag set.
A tag set is a dict. A server matches if its tags are a superset:
A server tagged {'a': '1', 'b': '2'} matches the tag set {'a': '1'}.
The empty tag set {} matches any server.
apply_tag_sets(tag_sets: 'TagSets', selection: 'Selection') -> 'Selection'
All servers match a list of tag sets.
tag_sets is a list of dicts. The empty tag set {} matches any server,
and may be provided at the end of the list as a fallback. So
[{'a': 'value'}, {}] expresses a preference for servers tagged
{'a': 'value'}, but accepts any server if none matches the first
preference.
arbiter_server_selector(selection: 'Selection') -> 'Selection'
member_with_tags_server_selector(tag_sets: 'TagSets', selection: 'Selection') -> 'Selection'
All near-enough members matching the tag sets.
readable_server_selector(selection: 'Selection') -> 'Selection'
secondary_server_selector(selection: 'Selection') -> 'Selection'
secondary_with_tags_server_selector(tag_sets: 'TagSets', selection: 'Selection') -> 'Selection'
All near-enough secondaries matching the tag sets.
writable_preferred_server_selector(selection: 'Selection') -> 'Selection'
Like PrimaryPreferred but doesn't use tags or latency.
writable_server_selector(selection: 'Selection') -> 'Selection'
DATA
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
T = ~T
TYPE_CHECKING = False
TagSet = typing.Mapping[str, typing.Any]
TagSets = typing.Sequence[typing.Mapping[str, typing.Any]]
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\server_selectors.py
pymongo.server_type
Python Library Documentation: module pymongo.server_type in pymongo
NAME
pymongo.server_type - Type codes for MongoDB servers.
DATA
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\server_type.py
pymongo.socket_checker
Python Library Documentation: module pymongo.socket_checker in pymongo
NAME
pymongo.socket_checker - Select / poll helper
CLASSES
builtins.object
SocketChecker
class SocketChecker(builtins.object)
| SocketChecker() -> 'None'
|
| Methods defined here:
|
| __init__(self) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| select(self, sock: 'Any', read: 'bool' = False, write: 'bool' = False, timeout: 'Optional[float]' = 0) -> 'bool'
| Select for reads or writes with a timeout in seconds (or None).
|
| Returns True if the socket is readable/writable, False on timeout.
|
| socket_closed(self, sock: 'Any') -> 'bool'
| Return True if we know socket has been closed, False otherwise.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\socket_checker.py
pymongo.ssl_context
Python Library Documentation: module pymongo.ssl_context in pymongo
NAME
pymongo.ssl_context - A fake SSLContext implementation.
DATA
BLOCKING_IO_ERRORS = (<class 'ssl.SSLWantReadError'>, <class 'ssl.SSLW...
HAS_SNI = True
IS_PYOPENSSL = False
OP_NO_COMPRESSION = <Options.OP_NO_COMPRESSION: 131072>
OP_NO_RENEGOTIATION = <Options.OP_NO_RENEGOTIATION: 1073741824>
OP_NO_SSLv2 = <Options.OP_NO_SSLv2: 0>
OP_NO_SSLv3 = <Options.OP_NO_SSLv3: 33554432>
PROTOCOL_SSLv23 = <_SSLMethod.PROTOCOL_TLS_CLIENT: 16>
VERIFY_CRL_CHECK_LEAF = <VerifyFlags.VERIFY_CRL_CHECK_LEAF: 4>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\ssl_context.py
pymongo.ssl_support
Python Library Documentation: module pymongo.ssl_support in pymongo
NAME
pymongo.ssl_support - Support for SSL in PyMongo.
FUNCTIONS
get_ssl_context(certfile: 'Optional[str]', passphrase: 'Optional[str]', ca_certs: 'Optional[str]', crlfile: 'Optional[str]', allow_invalid_certificates: 'bool', allow_invalid_hostnames: 'bool', disable_ocsp_endpoint_check: 'bool', is_sync: 'bool') -> 'Union[_pyssl.SSLContext, _ssl.SSLContext]'
Create and return an SSLContext object.
DATA
BLOCKING_IO_ERRORS = (<class 'ssl.SSLWantReadError'>, <class 'ssl.SSLW...
BLOCKING_IO_LOOKUP_ERROR = (<class 'OpenSSL.SSL.WantReadError'>, <clas...
BLOCKING_IO_READ_ERROR = (<class 'OpenSSL.SSL.WantReadError'>, <class ...
BLOCKING_IO_WRITE_ERROR = (<class 'OpenSSL.SSL.WantWriteError'>, <clas...
CERT_NONE = <VerifyMode.CERT_NONE: 0>
CERT_REQUIRED = <VerifyMode.CERT_REQUIRED: 2>
HAVE_PYSSL = True
HAVE_SSL = True
IPADDR_SAFE = True
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
__annotations__ = {'BLOCKING_IO_ERRORS': 'tuple', 'BLOCKING_IO_READ_ER...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\ssl_support.py
pymongo.synchronous
Python Library Documentation: package pymongo.synchronous in pymongo
NAME
pymongo.synchronous
PACKAGE CONTENTS
aggregation
auth
auth_aws
auth_oidc
bulk
change_stream
client_bulk
client_session
collection
command_cursor
cursor
cursor_base
database
encryption
helpers
mongo_client
monitor
network
pool
server
settings
srv_resolver
topology
uri_parser
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\synchronous\__init__.py
pymongo.timeout
Python Library Documentation: function timeout in module pymongo
timeout(seconds: 'Optional[float]') -> 'ContextManager[None]'
**(Provisional)** Apply the given timeout for a block of operations.
.. note:: :func:`~pymongo.timeout` is currently provisional. Backwards
incompatible changes may occur before becoming officially supported.
Use :func:`~pymongo.timeout` in a with-statement::
with pymongo.timeout(5):
client.db.coll.insert_one({})
client.db.coll2.insert_one({})
When the with-statement is entered, a deadline is set for the entire
block. When that deadline is exceeded, any blocking pymongo operation
will raise a timeout exception. For example::
try:
with pymongo.timeout(5):
client.db.coll.insert_one({})
time.sleep(5)
# The deadline has now expired, the next operation will raise
# a timeout exception.
client.db.coll2.insert_one({})
except PyMongoError as exc:
if exc.timeout:
print(f"block timed out: {exc!r}")
else:
print(f"failed with non-timeout error: {exc!r}")
When nesting :func:`~pymongo.timeout`, the nested deadline is capped by
the outer deadline. The deadline can only be shortened, not extended.
When exiting the block, the previous deadline is restored::
with pymongo.timeout(5):
coll.find_one() # Uses the 5 second deadline.
with pymongo.timeout(3):
coll.find_one() # Uses the 3 second deadline.
coll.find_one() # Uses the original 5 second deadline.
with pymongo.timeout(10):
coll.find_one() # Still uses the original 5 second deadline.
coll.find_one() # Uses the original 5 second deadline.
:param seconds: A non-negative floating point number expressing seconds, or None.
:raises: :py:class:`ValueError`: When `seconds` is negative.
See `Limit Server Execution Time <https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/csot/#overview>`_ for more examples.
.. versionadded:: 4.2
pymongo.topology_description
Python Library Documentation: module pymongo.topology_description in pymongo
NAME
pymongo.topology_description - Represent a deployment of MongoDB servers.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
TopologyDescription
class TopologyDescription(builtins.object)
| TopologyDescription(topology_type: 'int', server_descriptions: 'dict[_Address, ServerDescription]', replica_set_name: 'Optional[str]', max_set_version: 'Optional[int]', max_election_id: 'Optional[ObjectId]', topology_settings: 'Any') -> 'None'
|
| Methods defined here:
|
| __init__(self, topology_type: 'int', server_descriptions: 'dict[_Address, ServerDescription]', replica_set_name: 'Optional[str]', max_set_version: 'Optional[int]', max_election_id: 'Optional[ObjectId]', topology_settings: 'Any') -> 'None'
| Representation of a deployment of MongoDB servers.
|
| :param topology_type: initial type
| :param server_descriptions: dict of (address, ServerDescription) for
| all seeds
| :param replica_set_name: replica set name or None
| :param max_set_version: greatest setVersion seen from a primary, or None
| :param max_election_id: greatest electionId seen from a primary, or None
| :param topology_settings: a TopologySettings
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| apply_selector(self, selector: 'Any', address: 'Optional[_Address]' = None, custom_selector: 'Optional[_ServerSelector]' = None, deprioritized_servers: 'Optional[list[ServerDescription]]' = None) -> 'list[ServerDescription]'
| List of servers matching the provided selector(s).
|
| :param selector: a callable that takes a Selection as input and returns
| a Selection as output. For example, an instance of a read
| preference from :mod:`~pymongo.read_preferences`.
| :param address: A server address to select.
| :param custom_selector: A callable that augments server
| selection rules. Accepts 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.
|
| .. versionadded:: 3.4
|
| check_compatible(self) -> 'None'
| Raise ConfigurationError if any server is incompatible.
|
| A server is incompatible if its wire protocol version range does not
| overlap with PyMongo's.
|
| has_readable_server(self, read_preference: '_ServerMode' = Primary()) -> 'bool'
| Does this topology have any readable servers available matching the
| given read preference?
|
| :param read_preference: an instance of a read preference from
| :mod:`~pymongo.read_preferences`. Defaults to
| :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
|
| .. note:: When connected directly to a single server this method
| always returns ``True``.
|
| .. versionadded:: 3.4
|
| has_server(self, address: '_Address') -> 'bool'
|
| has_writable_server(self) -> 'bool'
| Does this topology have a writable server available?
|
| .. note:: When connected directly to a single server this method
| always returns ``True``.
|
| .. versionadded:: 3.4
|
| reset(self) -> 'TopologyDescription'
| A copy of this description, with all servers marked Unknown.
|
| reset_server(self, address: '_Address') -> 'TopologyDescription'
| A copy of this description, with one server marked Unknown.
|
| server_descriptions(self) -> 'dict[_Address, ServerDescription]'
| dict of (address,
| :class:`~pymongo.server_description.ServerDescription`).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| candidate_servers
| List of Servers excluding deprioritized servers.
|
| common_wire_version
| Minimum of all servers' max wire versions, or None.
|
| has_known_servers
| Whether there are any Servers of types besides Unknown.
|
| heartbeat_frequency
|
| known_servers
| List of Servers of types besides Unknown.
|
| logical_session_timeout_minutes
| Minimum logical session timeout, or None.
|
| max_election_id
| Greatest electionId seen from a primary, or None.
|
| max_set_version
| Greatest setVersion seen from a primary, or None.
|
| readable_servers
| List of readable Servers.
|
| replica_set_name
| The replica set name.
|
| srv_max_hosts
|
| topology_type
| The type of this topology.
|
| topology_type_name
| The topology type as a human readable string.
|
| .. versionadded:: 3.4
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
updated_topology_description(topology_description: 'TopologyDescription', server_description: 'ServerDescription') -> 'TopologyDescription'
Return an updated copy of a TopologyDescription.
:param topology_description: the current TopologyDescription
:param server_description: a new ServerDescription that resulted from
a hello call
Called after attempting (successfully or not) to call hello on the
server at server_description.address. Does not modify topology_description.
DATA
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
List = typing.List
A generic version of list.
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
SERVER_TYPE = _ServerType(Unknown=0, Mongos=1, RSPrimary=2, RS...Other...
SRV_POLLING_TOPOLOGIES = (4, 3)
TOPOLOGY_TYPE = _TopologyType(Single=0, ReplicaSetNoPrimary=1, R...hPr...
__annotations__ = {'SRV_POLLING_TOPOLOGIES': 'tuple[int, int]'}
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\topology_description.py
pymongo.typings
Python Library Documentation: module pymongo.typings in pymongo
NAME
pymongo.typings - Type aliases used by PyMongo
FUNCTIONS
strip_optional(elem: 'Optional[_T]') -> '_T'
This function is to allow us to cast all the elements of an iterator from Optional[_T] to _T
while inside a list comprehension.
DATA
_Address = typing.Tuple[str, typing.Optional[int]]
_AgnosticMongoClient = typing.Union[ForwardRef('AsyncMongoClient'), Fo...
_CollationIn = typing.Union[typing.Mapping[str, typing.Any], ForwardRe...
_DocumentOut = typing.Union[typing.MutableMapping[str, typing.Any], Fo...
_DocumentType = ~_DocumentType
_DocumentTypeArg = ~_DocumentTypeArg
_Pipeline = typing.Sequence[typing.Mapping[str, typing.Any]]
__all__ = ['_DocumentOut', '_DocumentType', '_DocumentTypeArg', '_Addr...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\typings.py
pymongo.uri_parser
Python Library Documentation: module pymongo.uri_parser in pymongo
NAME
pymongo.uri_parser - Tools to parse and validate a MongoDB URI.
FUNCTIONS
parse_host(entity: 'str', default_port: 'Optional[int]' = 27017) -> '_Address'
Validates a host string
Returns a 2-tuple of host followed by port where port is default_port
if it wasn't specified in the string.
:param entity: A host or host:port string where host could be a
hostname or IP address.
:param default_port: The port number to use when one wasn't
specified in entity.
parse_ipv6_literal_host(entity: 'str', default_port: 'Optional[int]') -> 'tuple[str, Optional[Union[str, int]]]'
Validates an IPv6 literal host:port string.
Returns a 2-tuple of IPv6 literal followed by port where
port is default_port if it wasn't specified in entity.
:param entity: A string that represents an IPv6 literal enclosed
in braces (e.g. '[::1]' or '[::1]:27017').
:param default_port: The port number to use when one wasn't
specified in entity.
parse_uri(uri: 'str', default_port: 'Optional[int]' = 27017, validate: 'bool' = True, warn: 'bool' = False, normalize: 'bool' = True, connect_timeout: 'Optional[float]' = None, srv_service_name: 'Optional[str]' = None, srv_max_hosts: 'Optional[int]' = None) -> 'dict[str, Any]'
Parse and validate a MongoDB URI.
Returns a dict of the form::
{
'nodelist': <list of (host, port) tuples>,
'username': <username> or None,
'password': <password> or None,
'database': <database name> or None,
'collection': <collection name> or None,
'options': <dict of MongoDB URI options>,
'fqdn': <fqdn of the MongoDB+SRV URI> or None
}
If the URI scheme is "mongodb+srv://" DNS SRV and TXT lookups will be done
to build nodelist and options.
:param uri: The MongoDB URI to parse.
:param default_port: The port number to use when one wasn't specified
for a host in the URI.
:param validate: If ``True`` (the default), validate and
normalize all options. Default: ``True``.
:param warn: When validating, if ``True`` then will warn
the user then ignore any invalid options or values. If ``False``,
validation will error when options are unsupported or values are
invalid. Default: ``False``.
:param normalize: If ``True``, convert names of URI options
to their internally-used names. Default: ``True``.
:param connect_timeout: The maximum time in milliseconds to
wait for a response from the DNS server.
:param srv_service_name: A custom SRV service name
.. versionchanged:: 4.14
``options`` is now type ``dict`` as opposed to a ``_CaseInsensitiveDictionary``.
.. versionchanged:: 4.6
The delimiting slash (``/``) between hosts and connection options is now optional.
For example, "mongodb://example.com?tls=true" is now a valid URI.
.. versionchanged:: 4.0
To better follow RFC 3986, unquoted percent signs ("%") are no longer
supported.
.. versionchanged:: 3.9
Added the ``normalize`` parameter.
.. versionchanged:: 3.6
Added support for mongodb+srv:// URIs.
.. versionchanged:: 3.5
Return the original value of the ``readPreference`` MongoDB URI option
instead of the validated read preference mode.
.. versionchanged:: 3.1
``warn`` added so invalid options can be ignored.
parse_userinfo(userinfo: 'str') -> 'tuple[str, str]'
Validates the format of user information in a MongoDB URI.
Reserved characters that are gen-delimiters (":", "/", "?", "#", "[",
"]", "@") as per RFC 3986 must be escaped.
Returns a 2-tuple containing the unescaped username followed
by the unescaped password.
:param userinfo: A string of the form <username>:<password>
split_hosts(hosts: 'str', default_port: 'Optional[int]' = 27017) -> 'list[_Address]'
Takes a string of the form host1[:port],host2[:port]... and
splits it into (host, port) tuples. If [:port] isn't present the
default_port is used.
Returns a set of 2-tuples containing the host name (or IP) followed by
port number.
:param hosts: A string of the form host1[:port],host2[:port],...
:param default_port: The port number to use when one wasn't specified
for a host.
split_options(opts: 'str', validate: 'bool' = True, warn: 'bool' = False, normalize: 'bool' = True) -> 'MutableMapping[str, Any]'
Takes the options portion of a MongoDB URI, validates each option
and returns the options in a dictionary.
:param opt: A string representing MongoDB URI options.
:param validate: If ``True`` (the default), validate and normalize all
options.
:param warn: If ``False`` (the default), suppress all warnings raised
during validation of options.
:param normalize: If ``True`` (the default), renames all options to their
internally-used names.
validate_options(opts: 'Mapping[str, Any]', warn: 'bool' = False) -> 'MutableMapping[str, Any]'
Validates and normalizes options passed in a MongoDB URI.
Returns a new dictionary of validated and normalized options. If warn is
False then errors will be thrown for invalid options, otherwise they will
be ignored and a warning will be issued.
:param opts: A dict of MongoDB URI options.
:param warn: If ``True`` then warnings will be logged and
invalid options will be ignored. Otherwise invalid options will
cause errors.
DATA
__all__ = ['parse_userinfo', 'parse_ipv6_literal_host', 'parse_host', ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\uri_parser.py
pymongo.version
Error rendering doc: No Python documentation found for '4.17.0'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pymongo.version_tuple
Python Library Documentation: tuple object class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | DNS_IDAttributes | DNSPatternAttributes | IPAddress_IDAttributes | ... and 10 other subclasses | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
pymongo.write_concern
Python Library Documentation: module pymongo.write_concern in pymongo
NAME
pymongo.write_concern - Tools for working with write concerns.
DESCRIPTION
.. seealso:: This module is compatible with both the synchronous and asynchronous PyMongo APIs.
CLASSES
builtins.object
WriteConcern
class WriteConcern(builtins.object)
| WriteConcern(w: 'Optional[Union[int, str]]' = None, wtimeout: 'Optional[int]' = None, j: 'Optional[bool]' = None, fsync: 'Optional[bool]' = None) -> 'None'
|
| WriteConcern
|
| :param w: (integer or string) Used with replication, write operations
| will block until they have been replicated to the specified number
| or tagged set of servers. `w=<integer>` always includes the replica
| set primary (e.g. w=3 means write to the primary and wait until
| replicated to **two** secondaries). **w=0 disables acknowledgement
| of write operations and can not be used with other write concern
| options.**
| :param wtimeout: (integer) **DEPRECATED** 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.
| :param j: If ``True`` block until write operations have been committed
| to the journal. Cannot be used in combination with `fsync`. Write
| operations will fail with an exception if this option is used when
| the server is running without journaling.
| :param 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`.
|
|
| .. versionchanged:: 4.7
| Deprecated parameter ``wtimeout``, use :meth:`~pymongo.timeout`.
|
| Methods defined here:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __init__(self, w: 'Optional[Union[int, str]]' = None, wtimeout: 'Optional[int]' = None, j: 'Optional[bool]' = None, fsync: 'Optional[bool]' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __ne__(self, other: 'Any') -> 'bool'
| Return self!=value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| acknowledged
| If ``True`` write operations will wait for acknowledgement before
| returning.
|
| document
| The document representation of this write concern.
|
| .. note::
| :class:`WriteConcern` is immutable. Mutating the value of
| :attr:`document` does not mutate this :class:`WriteConcern`.
|
| is_server_default
| Does this WriteConcern match the server default.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
FUNCTIONS
validate_boolean(option: 'str', value: 'Any') -> 'bool'
Validates that 'value' is True or False.
DATA
DEFAULT_WRITE_CONCERN = WriteConcern()
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\pymongo\write_concern.py