MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
Updating Data in MongoDB
We can update data in a collection using update_one() method and update_many() method.Ā
Ā
update_one()Ā
update_one() method update first occurrence if document matching the query filter is found.Ā
Syntax :update_one(query, newvalues, upsert=False, bypass_document_validation=False, collation=None, array_filters=None, session=None)
ĀParameters:Ā
filter : A query that matches the document to update.
new_values : The modifications to apply.
upsert (optional): If āTrueā, perform an insert if no documents match the filter.
bypass_document_validation (optional) : If āTrueā, allows the write to opt-out of document level validation. Default is āFalseā.
collation (optional) : An instance of class: ā~pymongo.collation.Collationā. This option is only supported on MongoDB 3.4 and above.
array_filters (optional) : A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.
session (optional) : a class:ā~pymongo.client_session.ClientSessionā.hint (optional): An index to use to support the query predicate specified. This option is only supported on MongoDB 4.2 and above.
Example:
Sample database is as follows:Ā

import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database name
db = client["GFG"]
# Collection name
col = db["gfg"]
# Query to be updated
query = {"coursename": "SYSTEM DESIGN"}
# New value
newvalue = {"$set": {"coursename": "Computer network"}}
# Update the value
col.update_one(query, newvalue)
Output:

Method: update_many()Ā
update_many() method update all the documents matching the query filter.Ā
Ā
Syntax:Ā
update_many(query, newvalues, upsert=False, bypass_document_validation=False, collation=None, array_filters=None, session=None)
Parameters:
- āfilterā : A query that matches the document to update.
- ānew_valuesā : The modifications to apply.
- āupsertā (optional): If āTrueā, perform an insert if no documents match the filter.
- ābypass_document_validationā (optional) : If āTrueā, allows the write to opt-out of document level validation. Default is āFalseā.
- ācollationā (optional) : An instance of class: ā~pymongo.collation.Collationā. This option is only supported on MongoDB 3.4 and above.
- āarray_filtersā (optional) : A list of filters specifying which array elements an update should apply. Requires MongoDB 3.6+.
- āsessionā (optional) : a class:ā~pymongo.client_session.ClientSessionā.
Example:
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Database name
db = client["GFG"]
# Collection name
col = db["gfg"]
# Query to be updated
query = {"coursename": "SYSTEM DESIGN"}
# New value
newvalue = {"$set": {"coursename": "Computer network"}}
# Update the value
col.update_many(query, newvalue)
Output:
