pymongo – Python driver for MongoDB (original) (raw)
Toggle site navigation sidebar
Toggle table of contents sidebar
Toggle table of contents sidebar
Python driver for MongoDB.
pymongo.version = '4.13.2'¶
Current version of PyMongo.
pymongo.MongoClient¶
Alias for pymongo.mongo_client.MongoClient.
pymongo.AsyncMongoClient¶
Alias for pymongo.asynchronous.mongo_client.AsyncMongoClient.
pymongo.ReadPreference¶
Alias for pymongo.read_preferences.ReadPreference.
pymongo.has_c()¶
Is the C extension installed?
Return type:
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)¶
(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 (float | None) – A non-negative floating point number expressing seconds, or None.
Raises:
ValueError: When seconds is negative.
Return type:
ContextManager[None]
See Client Side Operation Timeout for more examples.
Added in version 4.2.
Sub-modules:
- pymongo async – Async Python driver for MongoDB
- AsyncMongoClient
- change_stream – Watch changes on a collection, database, or cluster
* AsyncChangeStream
* AsyncClusterChangeStream
* AsyncCollectionChangeStream
* AsyncDatabaseChangeStream - client_session – Logical sessions for sequential operations
* Causally Consistent Reads
* Transactions
* Snapshot Reads
* Classes
* AsyncClientSession
* SessionOptions
* TransactionOptions - collection – Collection level operations
* ReturnDocument
* AsyncCollection - command_cursor – Tools for iterating over MongoDB command results
* AsyncCommandCursor
* AsyncRawBatchCommandCursor - cursor – Tools for iterating over MongoDB query results
* AsyncCursor
* AsyncRawBatchCursor - database – Database level operations
* AsyncDatabase - mongo_client – Tools for connecting to MongoDB
* AsyncMongoClient
- auth_oidc – MONGODB-OIDC Authentication
- change_stream – Watch changes on a collection, database, or cluster
- client_options – Read only configuration options for a MongoClient.
- ClientOptions
* ClientOptions.auto_encryption_opts
* ClientOptions.codec_options
* ClientOptions.connect
* ClientOptions.direct_connection
* ClientOptions.event_listeners
* ClientOptions.heartbeat_frequency
* ClientOptions.load_balanced
* ClientOptions.local_threshold_ms
* ClientOptions.pool_options
* ClientOptions.read_concern
* ClientOptions.read_preference
* ClientOptions.replica_set_name
* ClientOptions.retry_reads
* ClientOptions.retry_writes
* ClientOptions.server_monitoring_mode
* ClientOptions.server_selection_timeout
* ClientOptions.timeout
* ClientOptions.write_concern
- ClientOptions
- client_session – Logical sessions for sequential operations
- Causally Consistent Reads
- Transactions
* Sharded Transactions - Snapshot Reads
* Snapshot Reads Limitations - Classes
- ClientSession
* ClientSession.abort_transaction()
* ClientSession.advance_cluster_time()
* ClientSession.advance_operation_time()
* ClientSession.client
* ClientSession.cluster_time
* ClientSession.commit_transaction()
* ClientSession.end_session()
* ClientSession.has_ended
* ClientSession.in_transaction
* ClientSession.operation_time
* ClientSession.options
* ClientSession.session_id
* ClientSession.start_transaction()
* ClientSession.with_transaction() - SessionOptions
* SessionOptions.causal_consistency
* SessionOptions.default_transaction_options
* SessionOptions.snapshot - TransactionOptions
* TransactionOptions.max_commit_time_ms
* TransactionOptions.read_concern
* TransactionOptions.read_preference
* TransactionOptions.write_concern
- collation – Tools for working with collations.
- Collation
- CollationStrength
* CollationStrength.PRIMARY
* CollationStrength.SECONDARY
* CollationStrength.TERTIARY
* CollationStrength.QUATERNARY
* CollationStrength.IDENTICAL - CollationAlternate
* CollationAlternate.NON_IGNORABLE
* CollationAlternate.SHIFTED - CollationCaseFirst
* CollationCaseFirst.UPPER
* CollationCaseFirst.LOWER
* CollationCaseFirst.OFF - CollationMaxVariable
* CollationMaxVariable.PUNCT
* CollationMaxVariable.SPACE
- collection – Collection level operations
- ASCENDING
- DESCENDING
- GEO2D
- GEOSPHERE
- HASHED
- TEXT
- ReturnDocument
* ReturnDocument.BEFORE
* ReturnDocument.AFTER - Collection
* Collection.full_name
* Collection.name
* Collection.database
* Collection.codec_options
* Collection.read_preference
* Collection.write_concern
* Collection.read_concern
* Collection.with_options()
* Collection.bulk_write()
* Collection.insert_one()
* Collection.insert_many()
* Collection.replace_one()
* Collection.update_one()
* Collection.update_many()
* Collection.delete_one()
* Collection.delete_many()
* Collection.aggregate()
* Collection.aggregate_raw_batches()
* Collection.watch()
* Collection.find()
* Collection.find_raw_batches()
* Collection.find_one()
* Collection.find_one_and_delete()
* Collection.find_one_and_replace()
* Collection.find_one_and_update()
* Collection.count_documents()
* Collection.estimated_document_count()
* Collection.distinct()
* Collection.create_index()
* Collection.create_indexes()
* Collection.drop_index()
* Collection.drop_indexes()
* Collection.list_indexes()
* Collection.index_information()
* Collection.create_search_index()
* Collection.create_search_indexes()
* Collection.drop_search_index()
* Collection.list_search_indexes()
* Collection.update_search_index()
* Collection.drop()
* Collection.rename()
* Collection.options()
* Collection.__getitem__()
* Collection.__getattr__()
- command_cursor – Tools for iterating over MongoDB command results
- cursor – Tools for iterating over MongoDB query results
- CursorType
* CursorType.NON_TAILABLE
* CursorType.TAILABLE
* CursorType.TAILABLE_AWAIT
* CursorType.EXHAUST - Cursor
* Cursor.__getitem__()
* Cursor.add_option()
* Cursor.address
* Cursor.alive
* Cursor.allow_disk_use()
* Cursor.batch_size()
* Cursor.clone()
* Cursor.close()
* Cursor.collation()
* Cursor.collection
* Cursor.comment()
* Cursor.cursor_id
* Cursor.distinct()
* Cursor.explain()
* Cursor.hint()
* Cursor.limit()
* Cursor.max()
* Cursor.max_await_time_ms()
* Cursor.max_scan()
* Cursor.max_time_ms()
* Cursor.min()
* Cursor.next()
* Cursor.remove_option()
* Cursor.retrieved
* Cursor.rewind()
* Cursor.session
* Cursor.skip()
* Cursor.sort()
* Cursor.to_list()
* Cursor.where() - RawBatchCursor
- CursorType
- database – Database level operations
- MECHANISMS
- Database
* Database.__getitem__()
* Database.__getattr__()
* Database.codec_options
* Database.read_preference
* Database.write_concern
* Database.read_concern
* Database.aggregate()
* Database.client
* Database.command()
* Database.create_collection()
* Database.cursor_command()
* Database.dereference()
* Database.drop_collection()
* Database.get_collection()
* Database.list_collection_names()
* Database.list_collections()
* Database.name
* Database.validate_collection()
* Database.watch()
* Database.with_options()
- driver_info
- encryption – Client-Side Field Level Encryption
- Algorithm
* Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic
* Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random
* Algorithm.INDEXED
* Algorithm.RANGE
* Algorithm.RANGEPREVIEW
* Algorithm.UNINDEXED - ClientEncryption
* ClientEncryption.add_key_alt_name()
* ClientEncryption.close()
* ClientEncryption.create_data_key()
* ClientEncryption.create_encrypted_collection()
* ClientEncryption.decrypt()
* ClientEncryption.delete_key()
* ClientEncryption.encrypt()
* ClientEncryption.encrypt_expression()
* ClientEncryption.get_key()
* ClientEncryption.get_key_by_alt_name()
* ClientEncryption.get_keys()
* ClientEncryption.remove_key_alt_name()
* ClientEncryption.rewrap_many_data_key() - QueryType
* QueryType.EQUALITY
* QueryType.RANGE
* QueryType.RANGEPREVIEW - RewrapManyDataKeyResult
* RewrapManyDataKeyResult.bulk_write_result
- Algorithm
- encryption_options – Automatic Client-Side Field Level Encryption
- errors – Exceptions raised by the pymongo package
- AutoReconnect
- BulkWriteError
* BulkWriteError.timeout - ClientBulkWriteException
* ClientBulkWriteException.error
* ClientBulkWriteException.partial_result
* ClientBulkWriteException.write_concern_errors
* ClientBulkWriteException.write_errors - CollectionInvalid
- ConfigurationError
- ConnectionFailure
- CursorNotFound
- DocumentTooLarge
- DuplicateKeyError
- EncryptedCollectionError
* EncryptedCollectionError.encrypted_fields - EncryptionError
* EncryptionError.cause
* EncryptionError.timeout - ExecutionTimeout
* ExecutionTimeout.timeout - InvalidName
- InvalidOperation
- InvalidURI
- NetworkTimeout
* NetworkTimeout.timeout - NotPrimaryError
- OperationFailure
* OperationFailure.code
* OperationFailure.details
* OperationFailure.timeout - ProtocolError
- PyMongoError
* PyMongoError.has_error_label()
* PyMongoError.timeout - ServerSelectionTimeoutError
* ServerSelectionTimeoutError.timeout - WTimeoutError
* WTimeoutError.timeout - WaitQueueTimeoutError
* WaitQueueTimeoutError.timeout - WriteConcernError
- WriteError
- mongo_client – Tools for connecting to MongoDB
- MongoClient
* MongoClient.close()
* MongoClient.topology_description
* MongoClient.address
* MongoClient.primary
* MongoClient.secondaries
* MongoClient.arbiters
* MongoClient.is_primary
* MongoClient.is_mongos
* MongoClient.nodes
* MongoClient.codec_options
* MongoClient.read_preference
* MongoClient.write_concern
* MongoClient.read_concern
* MongoClient.options
* MongoClient.start_session()
* MongoClient.list_databases()
* MongoClient.list_database_names()
* MongoClient.drop_database()
* MongoClient.get_default_database()
* MongoClient.get_database()
* MongoClient.server_info()
* MongoClient.watch()
* MongoClient.bulk_write()
* MongoClient.__getitem__()
* MongoClient.__getattr__()
- MongoClient
- monitoring – Tools for monitoring driver events.
- register()
- CommandListener
* CommandListener.failed()
* CommandListener.started()
* CommandListener.succeeded() - ServerListener
* ServerListener.closed()
* ServerListener.description_changed()
* ServerListener.opened() - ServerHeartbeatListener
* ServerHeartbeatListener.failed()
* ServerHeartbeatListener.started()
* ServerHeartbeatListener.succeeded() - TopologyListener
* TopologyListener.closed()
* TopologyListener.description_changed()
* TopologyListener.opened() - ConnectionPoolListener
* ConnectionPoolListener.connection_check_out_failed()
* ConnectionPoolListener.connection_check_out_started()
* ConnectionPoolListener.connection_checked_in()
* ConnectionPoolListener.connection_checked_out()
* ConnectionPoolListener.connection_closed()
* ConnectionPoolListener.connection_created()
* ConnectionPoolListener.connection_ready()
* ConnectionPoolListener.pool_cleared()
* ConnectionPoolListener.pool_closed()
* ConnectionPoolListener.pool_created()
* ConnectionPoolListener.pool_ready() - CommandStartedEvent
* CommandStartedEvent.command
* CommandStartedEvent.command_name
* CommandStartedEvent.connection_id
* CommandStartedEvent.database_name
* CommandStartedEvent.operation_id
* CommandStartedEvent.request_id
* CommandStartedEvent.server_connection_id
* CommandStartedEvent.service_id - CommandSucceededEvent
* CommandSucceededEvent.command_name
* CommandSucceededEvent.connection_id
* CommandSucceededEvent.database_name
* CommandSucceededEvent.duration_micros
* CommandSucceededEvent.operation_id
* CommandSucceededEvent.reply
* CommandSucceededEvent.request_id
* CommandSucceededEvent.server_connection_id
* CommandSucceededEvent.service_id - CommandFailedEvent
* CommandFailedEvent.command_name
* CommandFailedEvent.connection_id
* CommandFailedEvent.database_name
* CommandFailedEvent.duration_micros
* CommandFailedEvent.failure
* CommandFailedEvent.operation_id
* CommandFailedEvent.request_id
* CommandFailedEvent.server_connection_id
* CommandFailedEvent.service_id - ServerDescriptionChangedEvent
* ServerDescriptionChangedEvent.new_description
* ServerDescriptionChangedEvent.previous_description
* ServerDescriptionChangedEvent.server_address
* ServerDescriptionChangedEvent.topology_id - ServerOpeningEvent
* ServerOpeningEvent.server_address
* ServerOpeningEvent.topology_id - ServerClosedEvent
* ServerClosedEvent.server_address
* ServerClosedEvent.topology_id - TopologyDescriptionChangedEvent
* TopologyDescriptionChangedEvent.new_description
* TopologyDescriptionChangedEvent.previous_description
* TopologyDescriptionChangedEvent.topology_id - TopologyOpenedEvent
* TopologyOpenedEvent.topology_id - TopologyClosedEvent
* TopologyClosedEvent.topology_id - ServerHeartbeatStartedEvent
* ServerHeartbeatStartedEvent.awaited
* ServerHeartbeatStartedEvent.connection_id - ServerHeartbeatSucceededEvent
* ServerHeartbeatSucceededEvent.awaited
* ServerHeartbeatSucceededEvent.connection_id
* ServerHeartbeatSucceededEvent.duration
* ServerHeartbeatSucceededEvent.reply - ServerHeartbeatFailedEvent
* ServerHeartbeatFailedEvent.awaited
* ServerHeartbeatFailedEvent.connection_id
* ServerHeartbeatFailedEvent.duration
* ServerHeartbeatFailedEvent.reply - PoolCreatedEvent
* PoolCreatedEvent.address
* PoolCreatedEvent.options - PoolClearedEvent
* PoolClearedEvent.address
* PoolClearedEvent.interrupt_connections
* PoolClearedEvent.service_id - PoolClosedEvent
* PoolClosedEvent.address - ConnectionCreatedEvent
* ConnectionCreatedEvent.address
* ConnectionCreatedEvent.connection_id - ConnectionReadyEvent
* ConnectionReadyEvent.address
* ConnectionReadyEvent.connection_id
* ConnectionReadyEvent.duration - ConnectionClosedReason
* ConnectionClosedReason.ERROR
* ConnectionClosedReason.IDLE
* ConnectionClosedReason.POOL_CLOSED
* ConnectionClosedReason.STALE - ConnectionClosedEvent
* ConnectionClosedEvent.address
* ConnectionClosedEvent.connection_id
* ConnectionClosedEvent.reason - ConnectionCheckOutStartedEvent
* ConnectionCheckOutStartedEvent.address - ConnectionCheckOutFailedReason
* ConnectionCheckOutFailedReason.CONN_ERROR
* ConnectionCheckOutFailedReason.POOL_CLOSED
* ConnectionCheckOutFailedReason.TIMEOUT - ConnectionCheckOutFailedEvent
* ConnectionCheckOutFailedEvent.address
* ConnectionCheckOutFailedEvent.connection_id
* ConnectionCheckOutFailedEvent.duration
* ConnectionCheckOutFailedEvent.reason - ConnectionCheckedOutEvent
* ConnectionCheckedOutEvent.address
* ConnectionCheckedOutEvent.connection_id
* ConnectionCheckedOutEvent.duration - ConnectionCheckedInEvent
* ConnectionCheckedInEvent.address
* ConnectionCheckedInEvent.connection_id
- operations – Operation class definitions
- pool – Pool module for use with a MongoDB client.
- PoolOptions
* PoolOptions.appname
* PoolOptions.connect_timeout
* PoolOptions.driver
* PoolOptions.load_balanced
* PoolOptions.max_connecting
* PoolOptions.max_idle_time_seconds
* PoolOptions.max_pool_size
* PoolOptions.metadata
* PoolOptions.min_pool_size
* PoolOptions.non_default_options
* PoolOptions.server_api
* PoolOptions.socket_timeout
* PoolOptions.tls_allow_invalid_hostnames
* PoolOptions.wait_queue_timeout
- PoolOptions
- read_concern – Tools for working with read concern.
- read_preferences – Utilities for choosing which member of a replica set to read from.
- Primary
* Primary.document
* Primary.mode
* Primary.name - PrimaryPreferred
* PrimaryPreferred.document
* PrimaryPreferred.hedge
* PrimaryPreferred.max_staleness
* PrimaryPreferred.min_wire_version
* PrimaryPreferred.mode
* PrimaryPreferred.mongos_mode
* PrimaryPreferred.name
* PrimaryPreferred.tag_sets - Secondary
* Secondary.document
* Secondary.hedge
* Secondary.max_staleness
* Secondary.min_wire_version
* Secondary.mode
* Secondary.mongos_mode
* Secondary.name
* Secondary.tag_sets - SecondaryPreferred
* SecondaryPreferred.document
* SecondaryPreferred.hedge
* SecondaryPreferred.max_staleness
* SecondaryPreferred.min_wire_version
* SecondaryPreferred.mode
* SecondaryPreferred.mongos_mode
* SecondaryPreferred.name
* SecondaryPreferred.tag_sets - Nearest
* Nearest.document
* Nearest.hedge
* Nearest.max_staleness
* Nearest.min_wire_version
* Nearest.mode
* Nearest.mongos_mode
* Nearest.name
* Nearest.tag_sets - ReadPreference
* ReadPreference.PRIMARY
* ReadPreference.PRIMARY_PREFERRED
* ReadPreference.SECONDARY
* ReadPreference.SECONDARY_PREFERRED
* ReadPreference.NEAREST
- Primary
- results – Result class definitions
- BulkWriteResult
* BulkWriteResult.acknowledged
* BulkWriteResult.bulk_api_result
* BulkWriteResult.deleted_count
* BulkWriteResult.inserted_count
* BulkWriteResult.matched_count
* BulkWriteResult.modified_count
* BulkWriteResult.upserted_count
* BulkWriteResult.upserted_ids - ClientBulkWriteResult
* ClientBulkWriteResult.acknowledged
* ClientBulkWriteResult.bulk_api_result
* ClientBulkWriteResult.delete_results
* ClientBulkWriteResult.deleted_count
* ClientBulkWriteResult.has_verbose_results
* ClientBulkWriteResult.insert_results
* ClientBulkWriteResult.inserted_count
* ClientBulkWriteResult.matched_count
* ClientBulkWriteResult.modified_count
* ClientBulkWriteResult.update_results
* ClientBulkWriteResult.upserted_count - DeleteResult
* DeleteResult.acknowledged
* DeleteResult.deleted_count
* DeleteResult.raw_result - InsertManyResult
* InsertManyResult.acknowledged
* InsertManyResult.inserted_ids - InsertOneResult
* InsertOneResult.acknowledged
* InsertOneResult.inserted_id - UpdateResult
* UpdateResult.acknowledged
* UpdateResult.did_upsert
* UpdateResult.matched_count
* UpdateResult.modified_count
* UpdateResult.raw_result
* UpdateResult.upserted_id
- BulkWriteResult
- server_api – Support for MongoDB Stable API
- server_description – An object representation of a server the driver is connected to.
- ServerDescription
* ServerDescription.address
* ServerDescription.all_hosts
* ServerDescription.error
* ServerDescription.min_round_trip_time
* ServerDescription.primary
* ServerDescription.replica_set_name
* ServerDescription.retryable_reads_supported
* ServerDescription.retryable_writes_supported
* ServerDescription.round_trip_time
* ServerDescription.server_type
* ServerDescription.server_type_name
- ServerDescription
- topology_description – An object representation of a deployment of MongoDB servers.
- TopologyDescription
* TopologyDescription.apply_selector()
* TopologyDescription.check_compatible()
* TopologyDescription.common_wire_version
* TopologyDescription.has_known_servers
* TopologyDescription.has_readable_server()
* TopologyDescription.has_writable_server()
* TopologyDescription.known_servers
* TopologyDescription.logical_session_timeout_minutes
* TopologyDescription.max_election_id
* TopologyDescription.max_set_version
* TopologyDescription.readable_servers
* TopologyDescription.replica_set_name
* TopologyDescription.reset()
* TopologyDescription.reset_server()
* TopologyDescription.server_descriptions()
* TopologyDescription.topology_type
* TopologyDescription.topology_type_name
- TopologyDescription
- uri_parser – Tools to parse and validate a MongoDB URI
- write_concern – Tools for specifying write concern
- event_loggers – Example loggers
- CommandLogger
* CommandLogger.failed()
* CommandLogger.started()
* CommandLogger.succeeded() - ConnectionPoolLogger
* ConnectionPoolLogger.connection_check_out_failed()
* ConnectionPoolLogger.connection_check_out_started()
* ConnectionPoolLogger.connection_checked_in()
* ConnectionPoolLogger.connection_checked_out()
* ConnectionPoolLogger.connection_closed()
* ConnectionPoolLogger.connection_created()
* ConnectionPoolLogger.connection_ready()
* ConnectionPoolLogger.pool_cleared()
* ConnectionPoolLogger.pool_closed()
* ConnectionPoolLogger.pool_created()
* ConnectionPoolLogger.pool_ready() - HeartbeatLogger
* HeartbeatLogger.failed()
* HeartbeatLogger.started()
* HeartbeatLogger.succeeded() - ServerLogger
* ServerLogger.closed()
* ServerLogger.description_changed()
* ServerLogger.opened() - TopologyLogger
* TopologyLogger.closed()
* TopologyLogger.description_changed()
* TopologyLogger.opened()
- CommandLogger