In this MongoDB tutorial, we learn how to connect to a MongoDB instance from a Python application using the PyMongo driver. We install the driver, create a MongoClient, use a MongoDB connection URI, verify the connection with a ping command, and close the client after the work is complete.

Connect Python application to MongoDB using PyMongo

To connect to MongoDB from Python Application, follow these steps. You need Python installed, a running MongoDB deployment, and a connection string such as mongodb://127.0.0.1:27017/ for a local server or a MongoDB Atlas URI for a cloud cluster.

PyMongo is the official MongoDB driver for Python applications. The MongoDB documentation covers connection strings, MongoClient, and connection options in its PyMongo connection guide.

1. Install PyMongo driver for a Python MongoDB connection

PyMongo contains tools for working with MongoDB.

To install PyMongo in Linux/OS X, use pip as shown below.

pip install pymongo

Console Output

root@tutorialkart:/home/arjun# pip install pymongo
Collecting pymongo
  Downloading pymongo-3.5.1-cp27-cp27mu-manylinux1_x86_64.whl (368kB)
    100% |????????????????????????????????| 368kB 13kB/s 
Installing collected packages: pymongo
Successfully installed pymongo-3.5.1

In current Python projects, it is usually better to run pip through Python itself. This installs the package into the same Python environment that runs your script.

</>
Copy
python -m pip install pymongo

If you connect with an Atlas SRV URI that starts with mongodb+srv://, install the SRV extras as well.

</>
Copy
python -m pip install "pymongo[srv]"

To install PyMongo on Windows, use installer available at https://pypi.python.org/pypi/pymongo/.

After installation, you can verify that PyMongo is available from your Python environment.

</>
Copy
python -m pip show pymongo

2. Import MongoClient in a Python script

In you Python Script, import MongoClient that acts as a Client from Python to MongoDB.

</>
Copy
from pymongo import MongoClient

You may also import PyMongo error classes when you want to catch connection failures clearly.

</>
Copy
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError

3. Create MongoClient with a MongoDB connection URI

Following is the syntax to create a MongoClient in Python.

</>
Copy
client = MongoClient(URI);

URI is where the MongoDB instance runs.

Example : mongodb://192.168.1.154:27017

Note : If URI is not specified, it tries to connect to MongoDB instance at localhost on port 27017.

For a local MongoDB server, the connection URI normally uses the mongodb:// scheme, host, and port.

</>
Copy
client = MongoClient("mongodb://127.0.0.1:27017/")

The MongoClient documentation explains how the constructor accepts a MongoDB URI and how connection options can be added to the URI or passed as keyword arguments.

4. Verify the MongoDB connection from Python with ping

If there is no exception thrown during MongoClient creation, your MongoClient is successfully connected to MongoDB.

In modern PyMongo usage, creating the MongoClient object alone should not be treated as a full connection test. PyMongo opens sockets when needed, so the recommended practical check is to run a simple server command such as ping. MongoDB documents ping as a no-op command that tests whether the server is responding.

</>
Copy
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure

client = MongoClient("mongodb://127.0.0.1:27017/", serverSelectionTimeoutMS=5000)

try:
    client.admin.command("ping")
    print("Connected to MongoDB")
except ConnectionFailure as err:
    print(f"Could not connect to MongoDB: {err}")
finally:
    client.close()

The serverSelectionTimeoutMS option keeps the example from waiting too long when the server is not reachable. For scripts and tutorials, a short timeout makes connection problems easier to see.

Connected to MongoDB

5. Close or reuse MongoClient after MongoDB operations

Once you are done with the MongoDB Operations, close the connection between MongoClient and MongoDB Daemon Service.

</>
Copy
client.close();

For a short Python script, closing the client at the end is simple and clear. For a long-running web application, create one client when the application starts and reuse it instead of creating a new client for every request.

Python MongoDB connection example for localhost

In the following Python program, we establish a connection to MongoDB instance running at mongodb://127.0.0.1:27017 from Python using MongoClient.

py-mongo-client.py

from pymongo import MongoClient
client = MongoClient("mongodb://127.0.0.1:27017")
print("Connection Successful")
client.close()

Console Output

arjun@tutorialkart:~/workspace/python$ python py-mongo-client.py 
Connection Successful

The example above shows that the Python script ran and created a MongoClient object. To confirm that the MongoDB server is reachable, use the ping version below.

Python MongoDB connection example with ping and timeout

The following example is safer for real troubleshooting because it sends a command to the server. If MongoDB is stopped, the port is blocked, or the URI is wrong, the script prints the error instead of reporting success too early.

py-mongo-ping.py

</>
Copy
from pymongo import MongoClient
from pymongo.errors import PyMongoError

uri = "mongodb://127.0.0.1:27017/"
client = MongoClient(uri, serverSelectionTimeoutMS=5000)

try:
    client.admin.command("ping")
    print("MongoDB connection is working")
except PyMongoError as err:
    print(f"MongoDB connection failed: {err}")
finally:
    client.close()

Output when the MongoDB server responds

MongoDB connection is working

Connect Python to MongoDB Atlas using a connection string

When MongoDB is hosted on Atlas, copy the connection string from the Atlas cluster page and use it as the URI. Keep the URI outside your source code when it contains a username and password. An environment variable is a common approach for local scripts and deployment pipelines.

</>
Copy
export MONGODB_URI='mongodb+srv://username:password@cluster-name.mongodb.net/?retryWrites=true&w=majority'
</>
Copy
import os
from pymongo import MongoClient

uri = os.environ["MONGODB_URI"]
client = MongoClient(uri, serverSelectionTimeoutMS=5000)

client.admin.command("ping")
print("Connected to MongoDB Atlas")

client.close()

For Atlas connections, also check that the database user exists, the password is correct, and the client IP address is allowed in the Atlas network access settings. A connection string with mongodb+srv:// needs the SRV dependency installed through pymongo[srv].

Select a MongoDB database and collection in Python after connecting

After the connection is verified, use the client to select a database and collection. MongoDB stores data as documents inside collections, so a quick insert and find operation is a useful end-to-end check.

</>
Copy
from pymongo import MongoClient

client = MongoClient("mongodb://127.0.0.1:27017/")

db = client["school"]
students = db["students"]

students.insert_one({"name": "Anika", "class": "10"})
student = students.find_one({"name": "Anika"})

print(student)

client.close()

Sample output

{'_id': ObjectId('...'), 'name': 'Anika', 'class': '10'}

Fix common PyMongo connection errors in Python

Most connection problems come from the URI, server availability, authentication, or network access. Use the points below before changing application logic.

  • ServerSelectionTimeoutError: MongoDB could not be reached within the timeout. Check whether the server is running, the host and port are correct, and the firewall allows the connection.
  • Authentication failed: Check the username, password, authentication database, and special characters in the password. Special characters in a URI password may need URL encoding.
  • DNS error with mongodb+srv: Install PyMongo with SRV support by using python -m pip install "pymongo[srv]".
  • Atlas network error: Add your current IP address to the Atlas access list and confirm that the cluster is active.
  • Script works locally but fails in deployment: Confirm that the deployment environment has the MONGODB_URI variable and can reach the MongoDB host.

FAQs on connecting MongoDB from Python with PyMongo

Does MongoClient connect to MongoDB immediately in Python?

No. Creating a MongoClient object prepares the client, but a server check happens when PyMongo performs an operation. Use client.admin.command("ping") when you want to verify that MongoDB is reachable.

What is the local MongoDB URI for PyMongo?

For a default local MongoDB server, use mongodb://127.0.0.1:27017/ or mongodb://localhost:27017/. The default MongoDB port is 27017.

How do I connect Python to MongoDB Atlas?

Copy the Atlas connection string, install PyMongo with SRV support if the URI starts with mongodb+srv://, store the URI securely, and pass it to MongoClient. Also confirm the Atlas database user and network access settings.

Should I close MongoClient after every MongoDB query?

Do not create and close a client for every single query in a long-running application. Reuse one client for the application lifetime. In a short script, close the client once at the end.

Why does PyMongo show ServerSelectionTimeoutError?

This usually means PyMongo could not find a reachable MongoDB server. Check the connection string, server status, port, firewall, DNS, Atlas IP access list, and credentials.

Editorial QA checklist for this Python MongoDB connection tutorial

  • Confirm that the tutorial uses python -m pip install pymongo for the current Python environment.
  • Confirm that a ping command is included before claiming that the MongoDB connection is working.
  • Confirm that local MongoDB and MongoDB Atlas connection strings are explained separately.
  • Confirm that passwords and Atlas connection strings are not hard-coded in production examples.
  • Confirm that common PyMongo errors mention URI, network access, authentication, and SRV dependency checks.

Summary: connect to MongoDB from Python using PyMongo

In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Python using PyMongo Driver. Install PyMongo, create a MongoClient with the correct MongoDB URI, run client.admin.command("ping") to verify the server response, use the required database and collection, and close the client when your script is done.