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 :
Install Python Driver – PyMongo
PyMongo contains tools for working with MongoDB.
To install PyMongo in Linux/OS X, use pip as shown below :pip installpymongo To install PyMongo on Windows, use installer at https://pypi.python.org/pypi/pymongo/.123456root@tutorialkart:/home/arjun# pip install pymongoCollecting pymongoDownloading pymongo-3.5.1-cp27-cp27mu-manylinux1_x86_64.whl (368kB)100% |????????????????????????????????| 368kB 13kB/sInstalling collected packages: pymongoSuccessfully installed pymongo-3.5.1Import MongoClient from pymongo
In you Python Script, import MongoClient that acts as a Client from Python to MongoDB.
123from pymongo import MongoClientCreate a connection to MongoDB Daemon Service using MongoClient
Following is the syntax to create a MongoClient in Python
123client = 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.MongoClient is Ready
If there is no exception thrown during MongoClient creation, your MongoClient is successfully connected to MongoDB.
Close connection to MongoDB
Once you are done with the MongoDB Operations, close the connection between MongoClient and MongoDB Daemon Service.
123client.close();
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 :
1 2 3 4 | from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") print("Connection Successful") client.close() |
1 2 | 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.