Insert and Update data in MongoDB using pymongo

Insert into MongoDB using PyMongo | Update MongoDB using Python

In this article, we dive in and see how to insert and update in MongoDB using PyMongo. PyMongo is the library used to work with MongoDB. Let’s first discuss how to insert into MongoDB using PyMongo.

Step 1: Create a connection using MongoClient.

conn = MongoClient('localhost', 27017)

If the database is installed in the local machine, provide IP as ‘localhost’, else provide the exact IP address.
27017 is the default port.

Step 2: Connect to Database.

dbconn = conn.dbname

This step will create a connection with the DB if exists else, it will create a new database if the database does not exist.

Step 3: Connect to Collection.

coll = dbconn.collectionname

This will connect to the collection and this step will create a new collection if the collection does not exist.

Step 4: Insert into the Collection.

from pymongo import MongoClient

try:
conn = MongoClient('localhost', 27017)
   print("Created conn successfully")
except:
   print("Error in connection")

# connect to database called airlinedb
dbconn= conn.airlinedb

# Create a collection: delayed_flight
collection = dbconn.delayed_flight

flight_delay_rec1={"flightnumber":300,"UniqueCarrier":"WN","DepTime":1000,"ArrTime":2000}
flight_delay_rec2={"flightnumber":310,"UniqueCarrier":"WP","DepTime":1200,"ArrTime":1500}

# Insert Data
rec1= collection.insert_one(flight_delay_rec1)
rec2= collection.insert_one(flight_delay_rec2)

# Print inserted data
cursor = collection.find()
for rec in cursor:
   print(rec)

Update data in MongoDB:

MongoDB has different methods to update a single record and multiple records.
update_one() : Used to update single record.
update_many() : Used to update multiple records.
These methods take 3 parameters.
The first parameter is a condition, the second parameter specifies modification data and the third parameter is an upsert parameter which is optional. The Upsert parameter is nothing but if a criterion does not match, then insert it into the DB.

from pymongo import MongoClient 
try: 
   conn = MongoClient()
   print("Created conn successfully")
except:
   print("Error in connection")
  
# connect to database called airlinedb
dbconn= conn.airlinedb
  
# Connect to delayed_flight collection
collection = dbconn.delayed_flight
  
# update all the employee data whose eid is 24 
result = collection.update_one( 
        {"flightnumber":300}, 
        { "$set":{ "UniqueCarrier":"WN-modifed"}}) 
  
# verify the updated record 
cursor = collection.find() 
for record in cursor: 
    print(record) 

In this blog, you have learned how to insert into MongoDB using PyMongo and how to update in MongoDB. Follow other tutorials for more information.

#mongodb insert document #Insert into MongoDB using PyMongo

Leave a Reply