DocsHub
CRUD Operations

Update

Learn how to update documents in MongoDB using updateOne, updateMany, replaceOne, and update operators.

Update

The third operation in CRUD is Update — modifying existing documents in a collection. MongoDB gives you three methods for this:

  • updateOne() — update the first document that matches the filter
  • updateMany() — update all documents that match the filter
  • replaceOne() — replace an entire document with a new one

Update Operators

Before looking at the methods, you need to understand update operators. In MongoDB, you never overwrite a document by passing a plain object — you use operators that tell MongoDB exactly what to change.

The most important ones:

OperatorWhat it does
$setSet the value of a field
$unsetRemove a field from the document
$incIncrement a number field by a given amount
$pushAdd a value to an array
$pullRemove a value from an array
$renameRename a field

We will use all of these in the examples below.


updateOne

updateOne() finds the first document that matches the filter and applies the update to it.

Syntax

db.collection.updateOne(filter, update)

Example — Update a student's age

db.students.updateOne(
  { name: "Ali Hassan" },       // filter — find this document
  { $set: { age: 17 } }         // update — change age to 17
)

Result

{
  acknowledged: true,
  matchedCount: 1,
  modifiedCount: 1
}
  • matchedCount — how many documents matched the filter
  • modifiedCount — how many documents were actually changed

Example — Update multiple fields at once

You can set multiple fields in one $set:

db.students.updateOne(
  { name: "Ali Hassan" },
  {
    $set: {
      age: 17,
      grade: "11th",
      "address.city": "Karachi"
    }
  }
)

Dot notation works inside $set too — this updates the city field inside the address object without touching anything else in the document.


$set

$set changes the value of a field. If the field does not exist, $set creates it.

// Add a new field — phone number — to a teacher
db.teachers.updateOne(
  { name: "Mr. Khan" },
  { $set: { phone: "0300-1234567" } }
)

The rest of the document stays exactly the same. Only the phone field is added.


$unset

$unset removes a field from a document completely.

// Remove the phone field from a teacher
db.teachers.updateOne(
  { name: "Mr. Khan" },
  { $unset: { phone: "" } }
)

The value you pass to $unset does not matter — MongoDB ignores it. Convention is to pass an empty string "".


$inc

$inc increments a number field by a given amount. Pass a negative number to decrement.

// Increase total students in Math course by 1
db.courses.updateOne(
  { code: "MATH-10" },
  { $inc: { totalStudents: 1 } }
)

// Decrease total students by 1
db.courses.updateOne(
  { code: "MATH-10" },
  { $inc: { totalStudents: -1 } }
)

Always use $inc to increment numbers — never read the current value, add to it in your code, and write it back. That approach causes race conditions when multiple operations run at the same time. $inc is atomic — MongoDB handles it safely.


$push

$push adds a value to an array field. If the array does not exist, MongoDB creates it.

// Add a new subject to a student's subjects array
db.students.updateOne(
  { name: "Ali Hassan" },
  { $push: { subjects: "Computer Science" } }
)

The subjects array now has one more item.

Push multiple values at once

Use $each with $push to add multiple values:

db.students.updateOne(
  { name: "Ali Hassan" },
  { $push: { subjects: { $each: ["Chemistry", "Urdu"] } } }
)

$pull

$pull removes a value from an array field.

// Remove Physics from a student's subjects
db.students.updateOne(
  { name: "Ali Hassan" },
  { $pull: { subjects: "Physics" } }
)

MongoDB removes every occurrence of "Physics" from the array.


$rename

$rename renames a field in the document.

// Rename 'phone' to 'contactNumber' in all teachers
db.teachers.updateMany(
  {},
  { $rename: { phone: "contactNumber" } }
)

updateMany

updateMany() updates all documents that match the filter — not just the first one.

Syntax

db.collection.updateMany(filter, update)

Example — Mark all 10th grade students as enrolled

db.students.updateMany(
  { grade: "10th" },
  { $set: { enrolled: true } }
)

Example — Add a new field to all documents

Pass an empty filter {} to match every document in the collection:

// Add a 'lastUpdated' field to every student
db.students.updateMany(
  {},
  { $set: { lastUpdated: new Date() } }
)

Result

{
  acknowledged: true,
  matchedCount: 4,
  modifiedCount: 4
}

Be very careful with updateMany({}, ...) — an empty filter matches every document in the collection. Always double-check your filter before running updateMany.


replaceOne

replaceOne() replaces an entire document with a new one. Only the _id is kept — everything else is replaced.

Syntax

db.collection.replaceOne(filter, replacement)

Example

db.students.replaceOne(
  { name: "Bilal Ahmed" },
  {
    name: "Bilal Ahmed",
    age: 17,
    grade: "11th",
    subjects: ["Math", "Physics"],
    enrolled: true
  }
)

The entire document is replaced. Any fields that existed before but are not in the new document are gone.

Use replaceOne() when you want to completely overwrite a document. Use updateOne() with $set when you only want to change specific fields. In most cases, updateOne() with operators is the better choice — it is safer and more precise.


Upsert

An upsert is a combination of update and insert. If a document matching the filter exists, MongoDB updates it. If no document matches, MongoDB inserts a new one.

Enable it by passing { upsert: true } as a third argument:

// Update the course if it exists, insert it if it does not
db.courses.updateOne(
  { code: "CS-10" },
  {
    $set: {
      title: "Computer Science",
      grade: "10th",
      credits: 3,
      totalStudents: 0
    }
  },
  { upsert: true }
)

If a course with code: "CS-10" exists, it gets updated. If not, a new course document is created.


School System Updates

Here are practical update operations for our school system:

// A student moved to a new city
db.students.updateOne(
  { name: "Sara Ahmed" },
  { $set: { "address.city": "Islamabad" } }
)

// A student passed to the next grade
db.students.updateOne(
  { name: "Ali Hassan" },
  { $set: { grade: "11th" } }
)

// Add a new subject to a student
db.students.updateOne(
  { name: "Ayesha Khan" },
  { $push: { subjects: "Computer Science" } }
)

// A student dropped a subject
db.students.updateOne(
  { name: "Umar Farooq" },
  { $pull: { subjects: "Chemistry" } }
)

// New student enrolled in a course — increment count
db.courses.updateOne(
  { code: "MATH-10" },
  { $inc: { totalStudents: 1 } }
)

// Mark all 11th grade students as having paid fees
db.students.updateMany(
  { grade: "11th" },
  { $set: { hasPaidFees: true } }
)

updateOne vs updateMany vs replaceOne

updateOneupdateManyreplaceOne
Documents affectedFirst match onlyAll matchesFirst match only
Uses operatorsYesYesNo — full replacement
Keeps other fieldsYesYesNo — replaces everything
Use whenUpdating one documentUpdating many at onceCompletely rewriting a document

When updating documents, always use the most specific filter possible. The more precise your filter, the less chance you accidentally update the wrong documents. If you are updating one specific document, filter by _id — it is guaranteed to match exactly one document.

On this page