MongoDB Update Operators

Update operators tell MongoDB exactly how to change a document. Without them, an update would replace the whole document. With them, you can change one field, add one number, or push one item into a list while every other field stays safe.

How an Update Works

db.collection.updateOne( FILTER , UPDATE )

FILTER  = which document to find      { name: "Pen" }
UPDATE  = what change to make         { $set: { price: 8 } }

The filter picks the target. The update operator describes the change. Use updateOne to change the first match and updateMany to change every match.

Sample Data

db.products.insertOne({
  name: "Notebook",
  price: 50,
  stock: 100,
  tags: ["paper", "school"]
})

Field Update Operators

$set: Change or Add a Field

db.products.updateOne({ name: "Notebook" }, { $set: { price: 55, brand: "Classic" } })

The price changes to 55. MongoDB adds the new field brand because the document did not have it before.

$unset: Remove a Field

db.products.updateOne({ name: "Notebook" }, { $unset: { brand: "" } })

The value after the field name does not matter. An empty string works fine.

$inc: Add to a Number

db.products.updateOne({ name: "Notebook" }, { $inc: { stock: -5 } })

A negative number subtracts. The stock drops from 100 to 95 in a single safe step. MongoDB completes the change without any other write interrupting it, so two shoppers buying at the same moment both get counted.

$mul: Multiply a Number

db.products.updateOne({ name: "Notebook" }, { $mul: { price: 1.1 } })

The price rises by ten percent.

$rename: Change a Field Name

db.products.updateOne({ name: "Notebook" }, { $rename: { stock: "quantity" } })

$min and $max: Keep the Lowest or Highest

db.products.updateOne({ name: "Notebook" }, { $max: { highestPrice: 60 } })

MongoDB replaces the field only when the new value is higher. The $min operator replaces the field only when the new value is lower. Both operators suit record keeping, such as a top score.

$currentDate: Stamp the Time

db.products.updateOne({ name: "Notebook" }, { $currentDate: { updatedAt: true } })

The server writes its current date and time into updatedAt.

Before and After Diagram

BEFORE:  { name: "Notebook", price: 50, stock: 100 }

         $set  { price: 55 }
         $inc  { stock: -5 }

AFTER:   { name: "Notebook", price: 55, stock: 95 }

Array Update Operators

$push: Add an Item to a List

db.products.updateOne({ name: "Notebook" }, { $push: { tags: "sale" } })

The tag list becomes ["paper", "school", "sale"]. Add several items in one command with $each:

db.products.updateOne({ name: "Notebook" }, { $push: { tags: { $each: ["new", "bulk"] } } })

$addToSet: Add Only If Missing

db.products.updateOne({ name: "Notebook" }, { $addToSet: { tags: "paper" } })

The tag paper already exists, so nothing changes. This operator prevents duplicate values in a list.

$pull: Remove Matching Items

db.products.updateOne({ name: "Notebook" }, { $pull: { tags: "sale" } })

$pop: Remove the First or Last Item

db.products.updateOne({ name: "Notebook" }, { $pop: { tags: 1 } })

The number 1 removes the last item, and -1 removes the first item.

Update One Item Inside an Array

The positional operator $ targets the element that matched the filter:

db.products.updateOne(
  { name: "Notebook", tags: "school" },
  { $set: { "tags.$": "student" } }
)

The tag school changes to student, and the other tags stay in place.

Upsert: Update or Insert

The upsert option inserts a new document when the filter finds nothing:

db.products.updateOne(
  { name: "Marker" },
  { $set: { price: 20, stock: 40 } },
  { upsert: true }
)

MongoDB creates the Marker product because none existed. A second run of the same command updates the existing document.

Quick Reference Table

OperatorJob
$setSets a field value
$unsetRemoves a field
$incAdds to a number
$mulMultiplies a number
$renameRenames a field
$min / $maxKeeps the lower or higher value
$pushAdds an item to an array
$addToSetAdds an item only when missing
$pullRemoves matching items
$popRemoves the first or last item

Common Mistakes

  • Leaving out the operator in updateOne raises an error. Use replaceOne when you want to swap the entire document on purpose.
  • Running updateMany with an empty filter changes every document in the collection.
  • Writing $set on an array field with a single value overwrites the whole list.

Summary

Update operators change documents in small, precise steps. Field operators such as $set, $inc, and $unset handle values. Array operators such as $push, $addToSet, and $pull handle lists. The upsert option combines update and insert into one command. Each operator runs as a single atomic action on the document, which keeps data consistent.

Leave a Comment

Your email address will not be published. Required fields are marked *