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.

https://www.mongodb.com/try/download/community .

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.

dbname='demoDB'
db = dbConn[dbname]

Show all the databases

print(dbConn.list_database_names())

Obtaining all the database names

dblist=dbConn.list_database_names()

Check if the databse exists in mongoDB.

db_name='PatientDB'

Connecting to a collection

collection_name='COVIDDailyTest'

Cheking if a collection exists

if collection_name in db.list_collection_names():
print("The collection exists.")
else:
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",
"Date":"2020-30-10"
"Active": 0,
"Confirmed": 434,
"Deceased": 0,
"Recovered": 434,},
{"District": "Telangana",
"Date":"2020-30-10"
"Active": 30,
"Confirmed": 400,
"Deceased": 0,
"Recovered": 800,},
{"District": "Kerala",
"Date":"2020-30-10"
"Active": 50,
"Confirmed": 200,
"Deceased": 0,
"Recovered": 600,}
]

Retieving all the records from collection

result= collection.find({}) 

Printing the third record

result[3]

Limit method to limit the query results

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

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
my_db_query={'Active':'337'}

Drop collection

# drops the entire collection named 'test collection'
collection_to_drop=db['test_collection']
collection_to_drop.drop()

Update collection

update_criteria={'Active':'340'}
new_values= { "$set": { "Active": "350" } }

x = collection.update_many(update_criteria, new_values)

print(x.modified_count)

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 ..!