Skip to content
Related Articles

Related Articles

How to update data in a Collection using Python?
  • Last Updated : 17 May, 2020

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:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :