pymongo – Python driver for MongoDB¶
Python driver for MongoDB.
- pymongo.version = '4.15.5'¶
-
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 Limit Server Execution Time for more examples.
Added in version 4.2.
Sub-modules:
pymongo async– Async Python driver for MongoDBAsyncMongoClientchange_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.ClientOptionsClientOptions.auto_encryption_optsClientOptions.codec_optionsClientOptions.connectClientOptions.direct_connectionClientOptions.event_listenersClientOptions.heartbeat_frequencyClientOptions.load_balancedClientOptions.local_threshold_msClientOptions.pool_optionsClientOptions.read_concernClientOptions.read_preferenceClientOptions.replica_set_nameClientOptions.retry_readsClientOptions.retry_writesClientOptions.server_monitoring_modeClientOptions.server_selection_timeoutClientOptions.timeoutClientOptions.write_concern
client_session– Logical sessions for sequential operations- Causally Consistent Reads
- Transactions
- Snapshot Reads
- Classes
ClientSessionClientSession.abort_transaction()ClientSession.advance_cluster_time()ClientSession.advance_operation_time()ClientSession.clientClientSession.cluster_timeClientSession.commit_transaction()ClientSession.end_session()ClientSession.has_endedClientSession.in_transactionClientSession.operation_timeClientSession.optionsClientSession.session_idClientSession.start_transaction()ClientSession.with_transaction()
SessionOptionsTransactionOptions
collation– Tools for working with collations.collection– Collection level operationsASCENDINGDESCENDINGGEO2DGEOSPHEREHASHEDTEXTReturnDocumentCollectionCollection.full_nameCollection.nameCollection.databaseCollection.codec_optionsCollection.read_preferenceCollection.write_concernCollection.read_concernCollection.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 resultsCursorTypeCursorCursor.__getitem__()Cursor.add_option()Cursor.addressCursor.aliveCursor.allow_disk_use()Cursor.batch_size()Cursor.clone()Cursor.close()Cursor.collation()Cursor.collectionCursor.comment()Cursor.cursor_idCursor.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.retrievedCursor.rewind()Cursor.sessionCursor.skip()Cursor.sort()Cursor.to_list()Cursor.where()
RawBatchCursor
database– Database level operationsMECHANISMSDatabaseDatabase.__getitem__()Database.__getattr__()Database.codec_optionsDatabase.read_preferenceDatabase.write_concernDatabase.read_concernDatabase.aggregate()Database.clientDatabase.command()Database.create_collection()Database.cursor_command()Database.dereference()Database.drop_collection()Database.get_collection()Database.list_collection_names()Database.list_collections()Database.nameDatabase.validate_collection()Database.watch()Database.with_options()
driver_infoencryption– Client-Side Field Level EncryptionAlgorithmClientEncryptionClientEncryption.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()
QueryTypeRewrapManyDataKeyResult
encryption_options– Automatic Client-Side Field Level Encryptionerrors– Exceptions raised by thepymongopackageAutoReconnectBulkWriteErrorClientBulkWriteExceptionCollectionInvalidConfigurationErrorConnectionFailureCursorNotFoundDocumentTooLargeDuplicateKeyErrorEncryptedCollectionErrorEncryptionErrorExecutionTimeoutInvalidNameInvalidOperationInvalidURINetworkTimeoutNotPrimaryErrorOperationFailureProtocolErrorPyMongoErrorServerSelectionTimeoutErrorWTimeoutErrorWaitQueueTimeoutErrorWriteConcernErrorWriteError
mongo_client– Tools for connecting to MongoDBMongoClientMongoClient.close()MongoClient.topology_descriptionMongoClient.addressMongoClient.primaryMongoClient.secondariesMongoClient.arbitersMongoClient.is_primaryMongoClient.is_mongosMongoClient.nodesMongoClient.codec_optionsMongoClient.read_preferenceMongoClient.write_concernMongoClient.read_concernMongoClient.optionsMongoClient.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()CommandListenerServerListenerServerHeartbeatListenerTopologyListenerConnectionPoolListenerConnectionPoolListener.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()
CommandStartedEventCommandSucceededEventCommandSucceededEvent.command_nameCommandSucceededEvent.connection_idCommandSucceededEvent.database_nameCommandSucceededEvent.duration_microsCommandSucceededEvent.operation_idCommandSucceededEvent.replyCommandSucceededEvent.request_idCommandSucceededEvent.server_connection_idCommandSucceededEvent.service_id
CommandFailedEventServerDescriptionChangedEventServerOpeningEventServerClosedEventTopologyDescriptionChangedEventTopologyOpenedEventTopologyClosedEventServerHeartbeatStartedEventServerHeartbeatSucceededEventServerHeartbeatFailedEventPoolCreatedEventPoolClearedEventPoolClosedEventConnectionCreatedEventConnectionReadyEventConnectionClosedReasonConnectionClosedEventConnectionCheckOutStartedEventConnectionCheckOutFailedReasonConnectionCheckOutFailedEventConnectionCheckedOutEventConnectionCheckedInEvent
operations– Operation class definitionspool– Pool module for use with a MongoDB client.PoolOptionsPoolOptions.appnamePoolOptions.connect_timeoutPoolOptions.driverPoolOptions.load_balancedPoolOptions.max_connectingPoolOptions.max_idle_time_secondsPoolOptions.max_pool_sizePoolOptions.metadataPoolOptions.min_pool_sizePoolOptions.non_default_optionsPoolOptions.server_apiPoolOptions.socket_timeoutPoolOptions.tls_allow_invalid_hostnamesPoolOptions.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 definitionsBulkWriteResultClientBulkWriteResultClientBulkWriteResult.acknowledgedClientBulkWriteResult.bulk_api_resultClientBulkWriteResult.delete_resultsClientBulkWriteResult.deleted_countClientBulkWriteResult.has_verbose_resultsClientBulkWriteResult.insert_resultsClientBulkWriteResult.inserted_countClientBulkWriteResult.matched_countClientBulkWriteResult.modified_countClientBulkWriteResult.update_resultsClientBulkWriteResult.upserted_count
DeleteResultInsertManyResultInsertOneResultUpdateResult
server_api– Support for MongoDB Stable APIserver_description– An object representation of a server the driver is connected to.ServerDescriptionServerDescription.addressServerDescription.all_hostsServerDescription.errorServerDescription.min_round_trip_timeServerDescription.primaryServerDescription.replica_set_nameServerDescription.retryable_reads_supportedServerDescription.retryable_writes_supportedServerDescription.round_trip_timeServerDescription.server_typeServerDescription.server_type_name
topology_description– An object representation of a deployment of MongoDB servers.TopologyDescriptionTopologyDescription.apply_selector()TopologyDescription.check_compatible()TopologyDescription.common_wire_versionTopologyDescription.has_known_serversTopologyDescription.has_readable_server()TopologyDescription.has_writable_server()TopologyDescription.known_serversTopologyDescription.logical_session_timeout_minutesTopologyDescription.max_election_idTopologyDescription.max_set_versionTopologyDescription.readable_serversTopologyDescription.replica_set_nameTopologyDescription.reset()TopologyDescription.reset_server()TopologyDescription.server_descriptions()TopologyDescription.topology_typeTopologyDescription.topology_type_name
uri_parser– Tools to parse and validate a MongoDB URIwrite_concern– Tools for specifying write concernevent_loggers– Example loggersCommandLoggerConnectionPoolLoggerConnectionPoolLogger.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()
HeartbeatLoggerServerLoggerTopologyLogger