Connect to MongoDB from Python
Connect to MongoDB from Python – In this MongoDB Tutorial, we shall learn to connect to MongoDB from Python Application.
To connect to MongoDB from Python Application, follow the below step by step guide :
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
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/.
2. Import MongoClient from pymongo
In you Python Script, import MongoClient that acts as a Client from Python to MongoDB.
from pymongo import MongoClientTry 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.
Example Python Script – To demonstrate Connection to MongoDB
Following is an example Python Script to demonstrate on how to establish a connection to MongoDB from Python by creating a MongoClient.
from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") print("Connection Successful") client.close()Try Online
arjun@tutorialkart:~/workspace/python$ python py-mongo-client.py Connection Successful
In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Python using PyMongo Driver.