Python MongoDB Update Document
Python provides two useful methods to update documents in a collection.
The update_one()
method is used to update the first occurrence of the document (It is has more than one document in the result).
The update_many()
method is used to update many documents in the result.
Both methods takes two arguments, which is:
- Query Object :- A query objective define which document to update
- Value Object :- It defines document's new values
We will take a sample collection called "emp" from "mydatabase" and it contains four columns ("id", "name", "city", and "salary") and five documents.
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'london', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
Update One Document in Collection - The update_one Method
Using the update_one()
method, you can update the record or document, as it is called in MongoDB.
Note : Only the first occurrence has been updated if the query discovers more than one record.
Example :- Change the city from "london" to "new york" :
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "city": "london" }
newvalues = { "$set": { "city": "new york" } }
mycol.update_one(myquery, newvalues)
for x in mycol.find():
print(x)
Output :-
{'_id': 2, 'name': 'bb', 'city': 'tokyo', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'new york', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'london', 'salary': 1000}
Note: There are two documents are selected by our query. But it updated only one document.
Related Links
Update Many Documents - The update_many() Method
Use the update_many()
function to update all documents which fulfil the query criteria.
Example :- Update city to "berlin" for all the documents where the salary less than 5000.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["emp"]
myquery = { "salary": {"$lt" : 5000} }
newvalues = { "$set": { "city": "berlin" } }
x = mycol.update_many(myquery, newvalues)
print(x.modified_count, "documents updated.")
for x in mycol.find():
print(x)
Output :-
{'_id': 1, 'name': 'aa', 'city': 'berlin', 'salary': 2000}
{'_id': 2, 'name': 'bb', 'city': 'berlin', 'salary': 3500}
{'_id': 3, 'name': 'cc', 'city': 'new york', 'salary': 7000}
{'_id': 4, 'name': 'dd', 'city': 'paris', 'salary': 6000}
{'_id': 5, 'name': 'ee', 'city': 'berlin', 'salary': 1000}
Related Links