Open In App

Insert and Update Data - Python MongoDB

Last Updated : 02 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In MongoDB, insertion refers to adding new documents into a collection, while updating allows modifying existing documents. These operations are essential for managing dynamic datasets. With PyMongo library in Python, users can perform these tasks efficiently by establishing a connection to the database, creating or accessing collections and executing commands to insert or update data.

Insert data

Inserting data involves defining documents as dictionaries and adding them to a collection using insert_one() or insert_many(). Each inserted document automatically gets a unique _id field.

1. Use insert_one() for a single document.

collection.insert_one(doc1)

Parameter: doc1 represents a dictionary

2. Use insert_many() for multiple document.

collection.insert_many([doc1, doc2, doc3.....])

Parameter: [doc1, doc2, doc3,....] represents a list of dictionary

Viewing Inserted Documents

To view the inserted documents, MongoDB provides the find() method, which retrieves documents from a specific collection.

cursor = collection.find()
for doc in cursor:
print(doc)

Note: find() method works only within a single collection. It does not support querying across multiple collections simultaneously.

Let's see Example of Insertion of Data:- 

Python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
print("Connected successfully!")

# Access database and collection
db = client["mydatabase"]
collection = db["my_gfg_collection"]

# Documents to insert
emp_rec1 = {
    "name": "Mr. Geek",
    "eid": 24,
    "location": "Delhi"
}
emp_rec2 = {
    "name": "Mr. Shaurya",
    "eid": 14,
    "location": "Delhi"
}

# Insert documents
rec_id1 = collection.insert_one(emp_rec1)
rec_id2 = collection.insert_one(emp_rec2)

print("Data inserted with record IDs:")
print("Record 1 ID:", rec_id1.inserted_id)
print("Record 2 ID:", rec_id2.inserted_id)

# Display inserted documents
print("\nInserted records:")
for record in collection.find():
    print(record)

Output

insertdata_output
Snapshot of Terminal showing output of Insert Data

Update data

Updating data involves modifying existing documents in a collection using update_one() or update_many(). These methods require a filter to match documents and an update operation to specify the changes.

With pymongo, updates can be easily applied using update operators like $set or $currentDate.

1. Use update_one() to update a single matching document

collection.update_one(filter, update)

Parameter:

  • filter a dictionary specifying the condition to match documents (e.g., {"eid": 101})
  • update a dictionary that defines the changes to apply (e.g., {"$set": {"name": "Updated Name"}})

2. Use update_many() to update all documents that match a condition

collection.update_many(filter, update)

Parameter:

  • filter a dictionary specifying the matching criteria
  • update a dictionary with update operators and values

Common Update Operators

1. $set: Updates the value of a specified field. If the field doesn't exist, it will be created.

{"$set": {"field": "value"}}

2. $currentDate: Sets the field to the current date or timestamp.

{"$currentDate": {"lastModified": True}}

Let's see Example of Updation of Data:- 

Python
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
print("Connected successfully!")

# Access database and collection
db = client["mydatabase"]
collection = db["my_gfg_collection"]

# Update all employee documents where eid is 24
result = collection.update_many(
    {"eid": 24},
    {
        "$set": {
            "name": "Mr. GeeksforGeeks"
        },
        "$currentDate": {
            "lastModified": True
        }
    }
)

# Display update result
print("Matched documents:", result.matched_count)
print("Modified documents:", result.modified_count)

# Display all records in the collection
print("\nUpdated records:")
for record in collection.find():
    print(record)

Output

updation_output
SNapshot of Terminal showing Update Data output

To find number of documents or entries in collection that are updated, use:

print(result.matched_count)

Here output would be 1.

Related Articles:


Article Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy