CPCODELAB
MongoDB

Updating Documents

11 min read

updateOne, updateMany, and Update Operators

Update operations take two arguments: a filter to match documents, and an update object using operators like $set, $inc, $push, and $pull to modify specific fields without replacing the whole document.

$set and $inc

js
// Update a single student's enrollment status
db.students.updateOne(
  { name: "Priya Singh" },
  { $set: { enrolled: true, updatedAt: new Date() } }
);

// Increment age of all enrolled students
db.students.updateMany(
  { enrolled: true },
  { $inc: { age: 1 } }
);

$push and $pull

js
// Add a skill tag to a student
db.students.updateOne(
  { name: "Riya Sharma" },
  { $push: { tags: "nodejs" } }
);

// Remove a tag
db.students.updateOne(
  { name: "Riya Sharma" },
  { $pull: { tags: "react" } }
);

Avoid replacing the update object with a plain document (no $ operators) — that would overwrite the entire document, losing all other fields.

Ready to test yourself?
Practice MongoDB— quiz & coding exercises