pymongo – Python driver for MongoDB#

Python driver for MongoDB.

pymongo.version = '4.6.3'#

Current version of PyMongo.

pymongo.MongoClient#

Alias for pymongo.mongo_client.MongoClient.

pymongo.ReadPreference#

Alias for pymongo.read_preferences.ReadPreference.

pymongo.has_c() bool#

Is the C extension installed?

pymongo.MIN_SUPPORTED_WIRE_VERSION#

The minimum wire protocol version PyMongo supports.

pymongo.MAX_SUPPORTED_WIRE_VERSION#

The maximum wire protocol version PyMongo supports.

pymongo.timeout(seconds: float | None) ContextManager[None]#

(Provisional) Apply the given timeout for a block of operations.

Note

timeout() is currently provisional. Backwards incompatible changes may occur before becoming officially supported.

Use 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 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.
Parameters:
  • seconds: A non-negative floating point number expressing seconds, or None.

Raises:

See Client Side Operation Timeout for more examples.

New in version 4.2.

Sub-modules: