Updating Documents in a Collection
Update queries in MongoDB consist of two parts: a document spec which informs the database of the set of documents to be updated, and the update document itself.
The first part, the document spec, is the same as the query document
which you use with find() or find_one().
The second part, the update document, can be used in two ways. The simplest is to supply the full document which will replace the matched document in the collection. For example, suppose you had the following document in your users collection:
user_doc = {
"username" : "janedoe",
"firstname" : "Jane",
"surname" : "Doe",
"dateofbirth" : datetime(1974, 4, 12),
"email" : "janedoe74@example.com",
"score" : 0
}Now let’s say you wish to update the document with username “janedoe” to change the email address to “janedoe74@example2.com”. We build a completely new document which is identical to the original, except for the new email address.
# first query to get a copy of the current document
import copy
old_user_doc = dbh.users.find_one({"username":"janedoe"})
new_user_doc = copy.deepcopy(old_user_doc)
# modify the copy to change the email address
new_user_doc["email"] = "janedoe74@example2.com"
# run the update query
# replace the matched document with the contents of new_user_doc
dbh.users.update({"username":"janedoe"}, new_user_doc, safe=True)Building the whole replacement document can be cumbersome, and worse, can introduce race conditions. Imagine you want to increment the score property ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access