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.
As with find_one_and_update()
, we first need to create a filter for the records that we want to update.
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)
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.