This MongoDB Update lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
update_one changes the first matching document. $set writes the fields you name and leaves the other fields in place.
Replacing the whole document is a different operation. Use $set when you mean to edit.
Example 1: Start here
update_one({"name": "Meera"}, {"$set": {"city": "Madurai"}}) is the call.
collection = [{"name": "Meera", "city": "Chennai"}] # a list; the values stay in this order
for doc in collection: # repeat the indented lines once per value
if doc["name"] == "Meera": # run the indented lines only when this is true
doc["city"] = "Madurai" # change this one field
print(collection)
Example 2: Filter the rows
MongoDB Update is easier to see as a list of records. The filter keeps every row whose seats value is at least 10.
rows = [{"topic": "MongoDB Update", "seats": 18}, {"topic": "SQL", "seats": 12}] # a list; the values stay in this order
print([row["topic"] for row in rows if row["seats"] >= 10]) # keep the items that pass the test
Example 3: Update one field
An update changes one field and leaves the rest of the record alone. On a database you would run an UPDATE or an update_one for the same change.
row = {"topic": "MongoDB Update", "seats": 18} # a dictionary; each key has one value
row["seats"] = row["seats"] + 1 # change this one field
print(row)
Example 4: Count the matches
Counting matches is the idea behind COUNT(*). Here the number 18 appears twice.
rows = [18, 4, 18] # a list; the values stay in this order
print(sum(1 for value in rows if value == 18)) # keep the items that pass the test
