Docs Menu
Docs Home
/ / /
PyMongo Driver

Connect to MongoDB

On this page

  • Overview
  • Sample Application
  • Connection
  • Local Deployment
  • Atlas
  • Replica Set
  • Network Compression
  • Compression Algorithms
  • zlib Compression Level
  • Server Selection
  • Stable API
  • Limit Server Execution Time
  • timeout Block
  • timeoutMS Connection Option

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.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have PyMongo installed.

  2. Copy the following code and paste it into a new .py file.

  3. 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:

1from pymongo import MongoClient
2
3try:
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
15except Exception as e:
16 raise Exception(
17 "The following error occurred: ", e)
1import asyncio
2from pymongo import AsyncMongoClient
3
4async 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
21asyncio.run(main())

The following sections describe how to connect to different targets, such as a local instance of MongoDB or a cloud-hosted instance on Atlas.

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)

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))

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)

The following sections describe how to connect to MongoDB while specifying network 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.

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.

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.

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.

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.

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.

Back

Get Started