A common operation in every application is that of updating a single record. For that, we'll use find_one_and_update()
provided by PyMongo.
The find_one_and_update()
method requires a filter to determine the record to be updated.
The following code tells us how to update a single record using PyMongo:
# Find the record you want to update and save the ID from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.pythonbicookbook customers = db.customers customers.find_one_and_update( {"first_name": "Bob", "last_name": "Smith"}, {'$set': {'contacted': False, 'updated_at': datetime.datetime.utcnow()}})
The first thing we do is create a filter for the update. In this recipe, we look for a record where the first_name
field is Bob
and the last_name
field is Smith
. Next, we tell PyMongo about the update operation that is to be applied. Here, we're telling PyMongo to set contacted to False,
and to set the updated_at
field to the current date and time. We then run the method against the customers
collection.
This is the first time we have seen the $set update
operator. As you may have guessed, $set
sets the value of a field in a document. For the full list of the update
operators, visit the MongoDB documentation: https://docs.mongodb.org/manual/reference/operator/update/.
An important note on using find_one_and_update()
—I suggest using this method only after you've retrieved the single record that you want to update so that you don't end up updating any other record. For instance, in a web application, if you find a single user's record, you would then use find_one_and_update()
to update his or her user record.