Skip to content
Related Articles

Related Articles

Improve Article

Update all Documents in a Collection using PyMongo

  • Last Updated : 03 Jun, 2020

MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational.

PyMongo contains tools which are used to interact with the MongoDB database. Now let’s see how to update all the documents in a collection.

Updating all Documents in a Collection

PyMongo includes an update_many() function which  updates all the documents which satisfy the given query.

update_many() accepts the following parameters –

  1.  filter – It is the first parameter which is a criteria according to which the documents that satisfy the query are updated.
  2. update operator- It is the second parameter which contains the information to be updated in the documents.
  3. upsert- (Optional) It is a boolean. If set to true and there is no document matching the filter, a new document is created.
  4. array_filters – (Optional) It is an array of filter documents to determine which array elements to modify for an update operation on an array field.
  5. bypass_document_validation – (Optional) A boolean which skips the document validation when set to True.
  6. collation – (Optional) specifies the language specific rules for the operation.
  7. session – (Optional) a ClientSession.

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

Now let’s understand through some examples.

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: 

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :