Updating multiple records using PyMongo

When you need to update many records at once, which can be the case when you need a new field added to all the existing records, use the update_many() function.

Getting ready

As with find_one_and_update(), we first need to create a filter for the records that we want to update.

How to do it…

The following code tells us how to update multiple records using PyMongo:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
customers = db.customers
result = customers.update_many(
            { 'first_name': {
'$exists': True }
},
            {'$currentDate': {
                'updated_at': { $type: "timestamp" }
         },
'$set': {
'contacted': False
             }})
print(result.matched_count)

How it works…

In this recipe, we are setting the contacted key to False for all the customer records that have a first name and updated_at to the time of the update. We then print out the count of records that were updated. As in previous recipes, we provide a filter as the first argument followed by the update to be performed.

Instead of manually setting the updated_at field, we use another update operator: $currentDate, which will set the given field, in this case updated_at, to the current timestamp using the $type operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset