Updating documents

In the following code block, you can see an example of updating a single document using the update_one helper method.

This operation matches one document in the search phase and modifies one document based on the operation to be applied to the matched documents:

>>> result = books.update_one({"isbn": "101"}, {"$set": {"price": 100}})
>>> print(result.matched_count)
1
>>> print(result.modified_count)
1

In a similar way to inserting documents, when updating documents, we can use update_one or update_many:

  • The first argument here is the filter document for matching the documents that will be updated
  • The second argument is the operation to be applied to the matched documents
  • The third (optional) argument is to use upsert=false (the default) or true, which is used to create a new document if it's not found

Another interesting argument is bypass_document_validation=false (the default) or true, which is optional. This will ignore validations (if there are any) for the documents in the collection.

The resulting object will have matched_count for the number of documents that matched the filter query, and modified_count for the number of documents that were affected by the update part of the query.

In our example, we are setting price=100 for the first book with isbn=101 through the $set update operator. A list of all update operators is displayed in the Update operators section later in this chapter.

If we don't use an update operator as the second argument, the contents of the matched document will be entirely replaced by the new document.
..................Content has been hidden....................

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