pymongo
– Python driver for MongoDB¶
Python driver for MongoDB.
- pymongo.version = '4.9'¶
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.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 MongoDBAsyncMongoClient
change_stream
– Watch changes on a collection, database, or clusterclient_session
– Logical sessions for sequential operationscollection
– Collection level operationscommand_cursor
– Tools for iterating over MongoDB command resultscursor
– Tools for iterating over MongoDB query resultsdatabase
– Database level operationsmongo_client
– Tools for connecting to MongoDB
auth_oidc
– MONGODB-OIDC Authenticationchange_stream
– Watch changes on a collection, database, or clusterclient_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
client_session
– Logical sessions for sequential operations- Causally Consistent Reads
- Transactions
- Snapshot Reads
- 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
TransactionOptions
collation
– Tools for working with collations.collection
– Collection level operationsASCENDING
DESCENDING
GEO2D
GEOSPHERE
HASHED
TEXT
ReturnDocument
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 resultscursor
– Tools for iterating over MongoDB query resultsCursorType
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
database
– Database level operationsMECHANISMS
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 EncryptionAlgorithm
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
RewrapManyDataKeyResult
encryption_options
– Automatic Client-Side Field Level Encryptionerrors
– Exceptions raised by thepymongo
packageAutoReconnect
BulkWriteError
ClientBulkWriteException
CollectionInvalid
ConfigurationError
ConnectionFailure
CursorNotFound
DocumentTooLarge
DuplicateKeyError
EncryptedCollectionError
EncryptionError
ExecutionTimeout
InvalidName
InvalidOperation
InvalidURI
NetworkTimeout
NotPrimaryError
OperationFailure
ProtocolError
PyMongoError
ServerSelectionTimeoutError
WTimeoutError
WaitQueueTimeoutError
WriteConcernError
WriteError
mongo_client
– Tools for connecting to MongoDBMongoClient
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__()
monitoring
– Tools for monitoring driver events.register()
CommandListener
ServerListener
ServerHeartbeatListener
TopologyListener
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
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
ServerDescriptionChangedEvent
ServerOpeningEvent
ServerClosedEvent
TopologyDescriptionChangedEvent
TopologyOpenedEvent
TopologyClosedEvent
ServerHeartbeatStartedEvent
ServerHeartbeatSucceededEvent
ServerHeartbeatFailedEvent
PoolCreatedEvent
PoolClearedEvent
PoolClosedEvent
ConnectionCreatedEvent
ConnectionReadyEvent
ConnectionClosedReason
ConnectionClosedEvent
ConnectionCheckOutStartedEvent
ConnectionCheckOutFailedReason
ConnectionCheckOutFailedEvent
ConnectionCheckedOutEvent
ConnectionCheckedInEvent
operations
– Operation class definitionspool
– 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
read_concern
– Tools for working with read concern.read_preferences
– Utilities for choosing which member of a replica set to read from.results
– Result class definitionsBulkWriteResult
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
InsertManyResult
InsertOneResult
UpdateResult
server_api
– Support for MongoDB Stable APIserver_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
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
uri_parser
– Tools to parse and validate a MongoDB URIwrite_concern
– Tools for specifying write concernevent_loggers
– Example loggersCommandLogger
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
ServerLogger
TopologyLogger