Python MongoDB – Update_many Query

MongoDB is  a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a python script. It needs both python and mongoDB to be installed on the system.

Update_many()

Update function has been deprecated in newer versions of  MongoDB (3.xx and above). Earlier update function could be used for both single updates and multiple using “multi = true”. But in newer versions of mongoDB it is recommended to use update_many() and update_one(). 

The major difference is that the user needs to plan ahead if the query is going to be updating single or multiple documents.

Syntax:

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>
   }
)

Update Operators in MongoDB



Setting Values:

  • $set: Used to set a fields value.
  • $setOnInsert: Update value only if a new document insertion.
  • $unset: Remove the field and its value.

Numeric Operators:

  • $inc: Increases the value by a given amount.
  • $min/$max: returns minimum or maximum of value.
  • $mul: multiplies the values by a given amount.

Miscellaneous Operators:

  • $currentDate: Updates value of a field to current date.
  • $rename: Renames a field

Sample Database:

Some use cases we are going to see in this article where updating many records can be useful: 

  1. Changing or incrementing several elements based on a condition.
  2. Inserting a new field to multiple or all documents.

Example 1: All the students with marks greater than 35 has been passed.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

from pymongo import MongoClient
  
  
# Creating an instance of MongoClient 
# on default localhost
client = MongoClient('mongodb://localhost:27017')
  
# Accessing desired database and collection
db = client.gfg
collection = db["classroom"]
  
# Update passed field to be true for all
# students with marks greater than 35
collection.update_many(
    {"marks": { "$gt": "35" } },
        {
            "$set": { "passed" : "True" }
        }
)

chevron_right


Database After Query: 

Example 2: New field called address added to all documents

Python

filter_none

edit
close

play_arrow

link
brightness_4
code

from pymongo import MongoClient
  
  
# Creating an instance of MongoClient 
# on default localhost
client = MongoClient('mongodb://localhost:27017')
  
# Accessing desired database and collection
db = client.gfg
collection = db["classroom"]
  
# Address filed to be added to all documents
collection.update_many(
        {},
        {"$set":
            {
                "Address": "value"
            }
        },
    
   # don't insert if no document found
   upsert=False,
   array_filters=None
   )

chevron_right


Database After query: 




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.