![]() |
VOOZH | about |
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.
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.
collection.insert_one(doc1)
Parameter: doc1 represents a dictionary
collection.insert_many([doc1, doc2, doc3.....])
Parameter: [doc1, doc2, doc3,....] represents a list of dictionary
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:-
Output
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.
collection.update_one(filter, update)
Parameter:
collection.update_many(filter, update)
Parameter:
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:-
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: