Docs Home → Develop Applications → Python Drivers → PyMongo
Choose a Connection Target
On this page
Overview
In this guide, you can learn how to use a connection string and MongoClient
object
to connect to different types of MongoDB deployments.
Atlas
To connect to a MongoDB deployment on Atlas, include the following elements in your connection string:
URL of your Atlas cluster
MongoDB username
MongoDB password
Then, pass your connection string to the MongoClient
constructor.
Tip
Follow the Atlas driver connection guide to retrieve your connection string.
When you connect to Atlas, we recommend using the Stable API client option to avoid breaking changes when Atlas upgrades to a new version of MongoDB Server. To learn more about the Stable API feature, see the Stable API page.
The following code shows how to use PyMongo to connect to an Atlas cluster. The
code also uses the server_api
option to specify a Stable API version.
from pymongo import MongoClient from pymongo.server_api import ServerApi # Replace the placeholder with your Atlas connection string uri = "<connection string>" # Create a MongoClient with a MongoClientOptions object to set the Stable API version client = MongoClient(uri, server_api=ServerApi( version='1', strict=True, deprecation_errors=True)) try: # Connect the client to the server (optional starting in v4.7) client.connect() # Send a ping to confirm a successful connection client.admin.command({'ping': 1}) print("Pinged your deployment. You successfully connected to MongoDB!") finally: # Ensures that the client will close when you finish/error client.close()
Local Deployments
To connect to a local MongoDB deployment, use localhost
as the hostname. By
default, the mongod
process runs on port 27017, though you can customize this for
your deployment.
The following code shows how to use PyMongo to connect to a local MongoDB deployment:
from pymongo import MongoClient uri = "mongodb://localhost:27017/" client = MongoClient(uri)
Replica Sets
To connect to a replica set, specify the hostnames (or IP addresses) and port numbers of the replica-set members in your connection string.
If you aren't able to provide a full list of hosts in the replica set, you can specify one or more of the hosts in the replica set and instruct PyMongo to perform automatic discovery to find the others. To instruct the driver to perform automatic discovery, perform one of the following actions:
Specify the name of the replica set as the value of the
replicaSet
parameter.Specify
false
as the value of thedirectConnection
parameter.Specify more than one host in the replica set.
In the following example, the driver uses a sample connection URI to connect to the
MongoDB replica set sampleRS
, which is running on port 27017
of three different
hosts, including host1
:
from pymongo import MongoClient uri = "mongodb://host1:27017/?replicaSet=sampleRS" client = MongoClient(uri)
Note
The MongoClient
constructor is non-blocking.
When you connect to a replica set, the constructor returns immediately while the
client uses background threads to connect to the replica set.
If you construct a MongoClient
and immediately print the string representation
of its nodes
attribute, the list might be empty while the client connects to
the replica-set members.
Initialization
To initialize a replica set, you must connect directly to a single member. To do so,
set the directConnection
connection
option to True
. You can do this in two ways: by passing an argument to the
MongoClient
constructor or through a parameter in your connection string.
Troubleshooting
Server Reports Wire Version X, PyMongo Requires Y
If you try to connect to MongoDB Server v3.4 or earlier, PyMongo might raise the following error:
pymongo.errors.ConfigurationError: Server at localhost:27017 reports wire version 5, but this version of PyMongo requires at least 6 (MongoDB 3.6).
This occurs when the driver version is too new for the server it's connecting to. To resolve this issue, upgrade your MongoDB deployment to v3.6 or later, or downgrade to PyMongo v3.x, which supports MongoDB Server v2.6 and later.
AutoReconnect
An AutoReconnect
exception indicates that a
failover has occurred. This means that
PyMongo has lost its connection to the original primary member
of the replica set, and its last operation might have failed.
When this error occurs, PyMongo automatically tries to find the new primary member for subsequent operations. To handle the error, your application must take one of the following actions:
Retry the operation that might have failed
Continue running, with the understanding that the operation might have failed
Important
PyMongo raises an AutoReconnect
error on all operations until the
replica set elects a new primary member.
API Documentation
To learn more about creating a MongoClient
object in PyMongo,
see the following API documentation: