Connect to MongoDB
On this page
Overview
This page contains code examples that show how to connect your Python application to MongoDB with various settings.
Tip
To learn more about the connection options on this page, see the link provided in each section.
To use a connection example from this page, copy the code example into the
sample application or your own application.
Be sure to replace all placeholders in the code examples, such as <hostname>
, with
the relevant values for your MongoDB deployment.
Sample Application
You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:
Ensure you have PyMongo installed.
Copy the following code and paste it into a new
.py
file.Copy a code example from this page and paste it on the specified lines in the file.
Select the Synchronous or Asynchronous tab to see the corresponding code:
1 from pymongo import MongoClient 2 3 try: 4 # start example code here 5 6 # end example code here 7 8 client.admin.command("ping") 9 print("Connected successfully") 10 11 # other application code 12 13 client.close() 14 15 except Exception as e: 16 raise Exception( 17 "The following error occurred: ", e)
1 import asyncio 2 from pymongo import AsyncMongoClient 3 4 async def main(): 5 try: 6 # start example code here 7 8 # end example code here 9 10 await client.admin.command("ping") 11 print("Connected successfully") 12 13 # other application code 14 15 await client.close() 16 17 except Exception as e: 18 raise Exception( 19 "The following error occurred: ", e) 20 21 asyncio.run(main())
Connection
The following sections describe how to connect to different targets, such as a local instance of MongoDB or a cloud-hosted instance on Atlas.
Local Deployment
The following code shows how to connect the connection string to connect to a local MongoDB deployment. Select the Synchronous or Asynchronous tab to see the corresponding code:
uri = "mongodb://localhost:27017/" client = MongoClient(uri)
uri = "mongodb://localhost:27017/" client = AsyncMongoClient(uri)
Atlas
The following code shows the connection string to connect to a deployment hosted on Atlas. Select the Synchronous or Asynchronous tab to see the corresponding code:
uri = "<Atlas connection string>" client = MongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True))
uri = "<Atlas connection string>" client = AsyncMongoClient(uri, server_api=pymongo.server_api.ServerApi( version="1", strict=True, deprecation_errors=True))
Replica Set
The following code shows the connection string to connect to a replica set. Select the Synchronous or Asynchronous tab to see the corresponding code:
uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>" client = MongoClient(uri)
uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>" client = AsyncMongoClient(uri)
Network Compression
The following sections describe how to connect to MongoDB while specifying network compression algorithms.
Compression Algorithms
The following tabs demonstrate how to specify all available compressors while connecting to MongoDB:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "snappy,zstd,zlib")
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=snappy,zstd,zlib") client = pymongo.MongoClient(uri)
client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "snappy,zstd,zlib")
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=snappy,zstd,zlib") client = pymongo.AsyncMongoClient(uri)
To learn more about specifying compression algorithms, see Specify Compression Algorithms in the Network Compression guide.
zlib Compression Level
The following tabs demonstrate how to specify a compression level for the zlib
compressor:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "zlib", zlibCompressionLevel=<zlib compression level>)
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=zlib" "zlibCompressionLevel=<zlib compression level>") client = pymongo.MongoClient(uri)
client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", compressors = "zlib", zlibCompressionLevel=<zlib compression level>)
uri = ("mongodb://<db_username>:<db_password>@<hostname>:<port>/?" "compressors=zlib" "zlibCompressionLevel=<zlib compression level>") client = pymongo.AsyncMongoClient(uri)
To learn more about setting the zlib compression level, see Specify Compression Algorithms in the Network Compression guide.
Server Selection
The following code shows a connection string that specifies a server selection function. Select the Synchronous or Asynchronous tab to see the corresponding code:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", server_selector=<selector function>)
client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname>:<port>", server_selector=<selector function>)
To learn more about customizing server selection, see Customize Server Selection.
Stable API
The following code shows how to specify Stable API settings for a connection.Select the Synchronous or Asynchronous tab to see the corresponding code:
from pymongo.server_api import ServerApi client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("<Stable API version>"))
from pymongo.server_api import ServerApi client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("<Stable API version>"))
To learn more about the Stable API, see Stable API.
Limit Server Execution Time
timeout Block
The following code shows how to set a client-side timeout by using the timeout()
method:
with pymongo.timeout(<timeout length>): # perform operations here
To learn more about client-side timeouts, see Limit Server Execution Time.
timeoutMS Connection Option
The following tabs demonstrate how to set a client-side timeout by using the timeoutMS
connection option:
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname@:<port>", timeoutMS=<timeout length>)
uri = "mongodb://<db_username>:<db_password>@<hostname:<port>/?timeoutMS=<timeout length>" client = pymongo.MongoClient(uri)
client = pymongo.AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname@:<port>", timeoutMS=<timeout length>)
uri = "mongodb://<db_username>:<db_password>@<hostname:<port>/?timeoutMS=<timeout length>" client = pymongo.AsyncMongoClient(uri)
To learn more about client-side timeouts, see Limit Server Execution Time.