MongoDB Python inserts and updates data

Prerequisite: MongoDB Python Fundamentals

We’ll start by looking at how to insert documents/entries in a database collection. Then, we’ll look at how to update existing documentation in MongoDB using the pymongo library in python. The update command helps us update the query data that has been inserted into the MongoDB database collection.

Insert data

We’ll start by inserting the data in MongoDB.

Step 1 – Establish the connection: Port Number Default: 27017

conn = MongoClient(‘localhost’, port-number)

If you use the default port number, which is 27017. Alternate connection method:

conn = MongoClient()

Step 2 – Create a database or switch to an existing one:

db = conn.dabasename

Create a collection or switch to an existing one:

collection = db.collection_name

Step 3 – Insert:

To insert data, create a dictionary object and insert the data into the database. Methods for inserting data:

insert_one() or insert_many()

After inserting to find documents within the collection, we use the find() command. find() method issues a query to retrieve data from a collection in MongoDB. All queries in MongoDB have scopes for a single collection.

Note: The ObjectId is different for each entry in the database collection.

Let’s understand data insertion with the help of code:-

# Python code to illustrate
# inserting data in MongoDB
from pymongo import MongoClient
  
try :
     conn = MongoClient()
     print ( "Connected successfully!!!" )
except :  
     print ( "Could not connect to MongoDB" )
  
# database
db = conn.database
  
# Created or Switched to collection names: my_gfg_collection
collection = db.my_gfg_collection
  
emp_rec1 = {
         "name" : "Mr.Geek" , "eid" : 24 , "location" : "delhi"
         }
emp_rec2 = {
         "name" : "Mr.Shaurya" , "eid" : 14 , "location" : "delhi"
         }
  
# Insert Data
rec_id1 = collection.insert_one(emp_rec1)
rec_id2 = collection.insert_one(emp_rec2)
  
print ( "Data inserted with record ids" , rec_id1, " " , rec_id2)
  
# Printing the data inserted
cursor = collection.find()
for record in cursor:
     print (record)

The output is as follows:

Connected successfully!!!
Data inserted with record ids    
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name':
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

Update data B in MongoD

Methods used: update_one() and update_many()

Parameters passed:

+ Filter documents to match the documents you want to update

+ Update the document to specify the modifications to be performed

+ Optional upsert parameters

After inserting the data in MongoDB, let’s update the employee data with ID 24

# Python code to illustrate
# updating data in MongoDB
# with Data of employee with id:24
from pymongo import MongoClient
  
try :
     conn = MongoClient()
     print ( "Connected successfully!!!" )
except :  
     print ( "Could not connect to MongoDB" )
  
# database
db = conn.database
  
# Created or Switched to collection names: my_gfg_collection
collection = db.my_gfg_collection
  
# update all the employee data whose eid is 24
result = collection.update_many(
         { "eid" : 24 }, {
                 "$set" :{
                         "name" : "Mr.lsbin"
                         }, "$currentDate" :{ "lastModified" : True }
                  
                 }
         )
  
  
  
print ( "Data updated with id" , result)
  
# Print the new record
cursor = collection.find()
for record in cursor:
     print (record)

The output is as follows:

Connected successfully!!!
Data updated with id 
{'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.lsbin', 'eid': 24, 'location': 
'delhi', 'lastModified': datetime.datetime(2017, 11, 7, 21, 19, 9, 698000)}
{'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 
'Mr.Shaurya', 'eid': 14, 'location': 'delhi'}

To find the number of documents or entries in a collection, update the usage.

print(result.matched_count)

The output here is 1.

First, your interview preparation enhances your data structure concepts with the Python DS course.