Working with MongoDB using Python

The post will help you to quickly undertand on how to manage a MongoDB instance using Python.

Topics covered

  1. Connect to DB instace
  2. Query DB
  3. Insert row(s)
  4. Update row(s)
  5. Sort the results
  6. Delete rows
  7. Delete Collection

First download and install Mongo DB from below link. .

Let’s get started.

Install python module for Mongod DB.

pip install pymongo

Connect to the MongoDB

#connecting to the locally running MongoDB Instance
dbConn = pymongo.MongoClient("mongodb://localhost:27017/")

Connecting to the database named demoDB present in the mongoDB
if the database is not present, it’ll autoamtically create it.

db = dbConn[dbname]

Show all the databases


Obtaining all the database names


Check if the databse exists in mongoDB.


Connecting to a collection


Cheking if a collection exists

if collection_name in db.list_collection_names():
print("The collection exists.")
print("The collection doesn't exist.")

Insert Operation

Inserting row into the collection

# Creating key value pairs for inserting into the DB

Inserting multiple rows at once

# creating key value pairs for inserting into the DB
my_rows = [
{"District": "Andhra Pradesh",
"Active": 0,
"Confirmed": 434,
"Deceased": 0,
"Recovered": 434,},
{"District": "Telangana",
"Active": 30,
"Confirmed": 400,
"Deceased": 0,
"Recovered": 800,},
{"District": "Kerala",
"Active": 50,
"Confirmed": 200,
"Deceased": 0,
"Recovered": 600,}

Retieving all the records from collection

result= collection.find({}) 

Printing the third record


Limit method to limit the query results

# printing only the five rows
result_total= collection.find({}).limit(5)
for res in result_total:

Retrieveing required columns

# retrieveing two columns
result_some= collection.find({}, {'District','Active'}).limit(5)

Finding the rows satisfying a given criteria

# printing all the rows where Active cases is 337

Sorting records

# We can sort the above results as well, this has been sorted in ascending order

Active= collection.find(my_db_query).sort('Active')

Deleting records

Deleting one record

# finding the rows satisfying a given criteria

Drop collection

# drops the entire collection named 'test collection'

Update collection

new_values= { "$set": { "Active": "350" } }

x = collection.update_many(update_criteria, new_values)


Hope now you have a fair idea about managing monog DB using pymongo . Please let me know if you encounter any issue or unable to follow the blog.I am always open to feedback. Cheers ..!