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 ...

Get Python Business Intelligence Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.