In this MongoDB tutorial, we learn how to connect to a MongoDB instance, from a Python application using pymongo library. We shall install the Python driver, create a connection, check if the client is ready, then close the connection to MongoDB instance.

Connect to MongoDB from Python

To connect to MongoDB from Python Application, follow these steps.

1. Install Python Driver – PyMongo

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

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

ADVERTISEMENT

2. Import MongoClient from pymongo

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

from pymongo import MongoClient
Try Online

3. Create a connection to MongoDB Daemon Service using MongoClient

Following is the syntax to create a MongoClient in Python.

client = MongoClient(URI);
Try Online

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.

4. MongoClient is Ready

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

5. Close connection to MongoDB

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

client.close();
Try Online

Example

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()
Try Online

Console Output

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

Conclusion

In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Python using PyMongo Driver.