Updating documents

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

Similar to inserting documents, when updating 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 upsert=false (default) or true, used to create a new document if it's not found

Another interesting argument is the optional bypass_document_validation=false (default) or true. 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 shown 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
18.117.77.76