Skip to content
Related Articles

Related Articles

Python MongoDB – Update_many Query

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 26 May, 2020

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




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" }
        }
)

Database After Query: 

Example 2: New field called address added to all documents

Python




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
   )

Database After query: 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!