MongoDB and Python


MongoDB is a widely used document database which is also a form of NoSQL DB. Python can interact with MongoDB through some python modules and create and manipulate data inside Mongo DB. In this article we will learn to do that. But MongoDB should already be available in your system before python can connect to it and run. To setup MongoDB in your system please visit our  MongoDB tutorial here..

Install pymongo

To interact with MongoDB we need the module names pymongo. Install it in your python environment using the below command.

pip install pymogo

Check the Existing DBs

We now use this python module to check for any existing DB. The below python program connects to the MongoDB service and gives a output of the list of DB names available.

Output

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

print(myclient.list_database_names())

Output

Running the above code gives us the following result −

['Mymdb', 'admin', 'config', 'local']

Check for collection

A collection is similar to a table in traditional rdbms. We can next check for collections present in a specific database using the below python program.

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
print(mndb.list_collection_names())

Output

Running the above code gives us the following result −

['newmongocoll']

Insert Document

The document in MongoDB is also comparable to a row in traditional RDBMS. In this program we see how to insert a document to MongoDB using a python program. First we connect to the DB and collections and then use a dictionary to put values of the document into the collection.

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
mycol = mndb['newmongocoll']

mydict = { "ID": "2", "Name": "Ramana" }

x = mycol.insert_one(mydict)
print(x)

Output

Running the above code gives us the following result −

<pymongo.results.InsertOneResult object at 0x000002CA92A920C0>

Find Documents

We can also query for documents present in MongoDB using find method available in pymongo.

Example

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mndb = myclient["Mymdb"]
mycol = mndb['newmongocoll']

for x in mycol.find():
print(x)

Output

Running the above code gives us the following result −

{'_id': ObjectId('5ef8b6f92d192421b78d32cb'), 'ID': '2', 'Name': 'Ramana'}

Updated on: 10-Jul-2020

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements