How to update data in a Collection using Python?

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 updated first occurrence if query is found. 

Syntax :update_one(query, newvalues)




Parameters:
Query: It is the query object. 
newvalues: It is the new values of the document. 

Example:

Sample Database:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output :
 

update_many() 

update_many() method update all the query values. 
 



Syntax: update_many(query, newvalues)


Parameters:
Query: It is the query object. 
newvalues: It is the new values of the document.

Example:
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.