Working with MongoDB using Python
The post will help you to quickly undertand on how to manage a MongoDB instance using Python.
Topics covered
- Connect to DB instace
- Query DB
- Insert row(s)
- Update row(s)
- Sort the results
- Delete rows
- 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'if dblist.index(db_name)==-1:
print ("This Databse doesn't exist")
else:
print ("This Databse exists")
Connecting to a collection
collection_name='COVIDDailyTest'collection=db[collection_name] # connectig to the collection itself present in the database.
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 DBmy_row = {"District": "Andhra Pradesh",
"Date":"2020-30-10"
"Active": 0,
"Confirmed": 434,
"Deceased": 0,
"Recovered": 434,}# inserting record into the collection
x = collection.insert_one(my_row) # printing the unique id for insert
print(x.inserted_id)
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,}
]# inserting records into the collection
x = collection.insert_many(my_rows)# printing the unique id for insert
print(x.inserted_ids)
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) # The second parameter in find() specifies which columns to choose
for res in result_some:
print(res)
Finding the rows satisfying a given criteria
# printing all the rows where Active cases is 337my_db_query={'Active':'337'}result_Active = collection.find(my_db_query)for res in result_Active:
print(res)
# printing all the rows where Active cases is greaterthan 337my_db_query={'Active':{'$gt':'337'}}result_Active= collection.find(my_db_query)
for res in result_Active:
print(res)
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')for res in Active:
print(res)
# we can sort the above results in descending order Active= collection.find(my_db_query).sort('Active',-1) for res in Active:
print(res)
Deleting records
Deleting one record
# finding the rows satisfying a given criteria
my_db_query={'Active':'337'}x=collection.delete_one(my_db_query) # the deletion step
print(x.deleted_count)# finding the rows satisfying a given criteria
my_db_query={'Active':'337'}# the deletion step
x=collection.delete_many(my_deb_query)
print(x.deleted_count)For deleting all documents of a collection, we can use collection.delete_many({})
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 ..!