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 installpymongo
    To install PyMongo on Windows, use installer 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.

  3. Create a connection to MongoDB Daemon Service using MongoClient

    Following is the syntax to create a MongoClient in Python

    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 :

 

Conclusion :

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