Start learning free

LESSON 53 OF 66 · NOSQL: MONGODB

Change Documents

Practice

To change a document, you call update_one with two dicts. The first is a filter that finds the document, like SQL's WHERE. The second is the change, written with an update operator: $set gives a field a new value, like UPDATE … SET, and $inc adds a number to it. Fields you don't name keep their values, and a dot path like "stock.count" reaches inside a nested dict.

Lists have operators of their own: $push adds a value at the end, like append, and $pull takes out the items equal to a value. Here are some of them on the Pen:

db.products.update_one({"name": "Pen"}, {"$set": {"price": 3}})
db.products.update_one({"name": "Pen"}, {"$inc": {"stock.count": 5}})
db.products.update_one({"name": "Pen"}, {"$push": {"tags": "school"}})

update_one changes only the first document the filter matches; update_many changes all of them. Both give back a result whose modified_count says how many documents changed. This lesson runs on an in-memory MongoDB that already holds the shop; the same code runs on a real MongoDB server.

Your code prints the changed Mug, then how many office products changed. The check then prints the office prices:

{'name': 'Mug', 'price': 14, 'category': 'kitchen', 'tags': ['gift', 'sale'], 'stock': {'count': 9, 'warehouse': 'A'}}
3
Office now: [{'name': 'Notebook', 'price': 8}, {'name': 'Pen', 'price': 3}, {'name': 'Stapler', 'price': 10}]

Your task: change the Mug: set its price to 14, take 1 off its stock.count, push "sale" onto its tags and pull "ceramic" out of them. Print the Mug with find_one and the projection {"_id": 0}. Then add 1 to the price of every office product with update_many, keep its answer in result and print result.modified_count.


Assignment
Follow the Coding Tutorial to change the Mug one operator at a time, then raise every office price with a single update_many.


Hint
Each update call takes the filter first, then one operator dict: {"$operator": {"field": value}}. To take one away with $inc, add -1.


STEP 1 OF 7
    Ctrl + Enter to check