Updating Documents
Change existing data with update operators like $set.
What you will learn
- Update one and many documents
- Use the $set operator
- Understand match-then-modify
updateOne and updateMany
An update takes two objects: a filter (which documents) and an update (what to change, using $set).
// Change Asha's city
db.users.updateOne(
{ name: "Asha" }, // filter: which document
{ $set: { city: "Mumbai" } } // update: what to change
)
// Give every user a "country" field
db.users.updateMany({}, { $set: { country: "India" } })Every update is match, then modify. The first object is the filter that finds the document(s); the second object says what to change. $set means “set these fields to these values” — it touches only the fields you name and leaves everything else untouched. updateOne changes just the first match; updateMany changes all matches, and here the empty filter {} means “every user”, so all of them get a country of India.
Note: Output:
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
matchedCount is how many documents the filter found, and modifiedCount is how many actually changed. For updateMany({}) on three users you would see both counts as 3.
- Write a filter to choose which document(s) to change.
- Write the update using
$set(and friends) to describe the new values. - MongoDB finds the matches and applies the change to each.
- It reports back how many it matched and how many it modified.
Watch out: Without $set, an update would replace the entire document with what you pass — wiping the other fields. Almost always use $set to change only specific fields.
Tip: Other handy update operators: $inc (increase a number), $push (add to an array), $unset (remove a field).
Q. Which operator changes specific fields without replacing the whole document?
✍️ Practice
- Update one document’s field using
$set. - Use
updateManyto add a field to every document.
🏠 Homework
- Increase the price of every product by using
$inc.