CRUD OperationsCore· 30 min read

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).

updateOne and updateMany with $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.

  1. Write a filter to choose which document(s) to change.
  2. Write the update using $set (and friends) to describe the new values.
  3. MongoDB finds the matches and applies the change to each.
  4. 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?

Answer: $set updates only the specified fields. Without it, the document would be entirely replaced by the new object.

✍️ Practice

  1. Update one document’s field using $set.
  2. Use updateMany to add a field to every document.

🏠 Homework

  1. Increase the price of every product by using $inc.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →