Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

MongoDB Update Operators

Field Update Operators

Update operators modify specific fields in a document without replacing the entire document. Always use them inside updateOne() or updateMany() to avoid accidentally overwriting your data.

$set, $unset, $inc, $mul, $rename, $min, $max, $currentDate
// $set — set field value (creates field if it doesn't exist)
db.users.updateOne(
  { email: "alice@example.com" },
  { $set: { age: 30, city: "Boston", "address.zip": "02101" } }
)

// $unset — remove a field from the document
db.users.updateOne(
  { email: "alice@example.com" },
  { $unset: { temporaryToken: "" } }
)

// $inc — increment (or decrement with negative value)
db.users.updateOne({ _id: ObjectId("...") }, { $inc: { loginCount: 1 } })
db.products.updateOne({ sku: "LAPTOP-001" }, { $inc: { stock: -1 } })

// $mul — multiply a field value
db.products.updateOne({ sku: "LAPTOP-001" }, { $mul: { price: 1.1 } })  // 10% price increase

// $rename — rename a field
db.users.updateMany({}, { $rename: { "fname": "firstName", "lname": "lastName" } })

// $min — update only if new value is less than current
db.scores.updateOne({ userId: "u1" }, { $min: { lowestScore: 45 } })

// $max — update only if new value is greater than current
db.scores.updateOne({ userId: "u1" }, { $max: { highScore: 98 } })

// $currentDate — set field to current date
db.users.updateOne(
  { email: "alice@example.com" },
  { $currentDate: { lastLogin: true, lastModified: { $type: "timestamp" } } }
)

Array Update Operators

$push, $pop, $pull, $addToSet
// $push — append a value to an array
db.users.updateOne(
  { email: "alice@example.com" },
  { $push: { hobbies: "gaming" } }
)

// $push with $each — append multiple values
db.users.updateOne(
  { email: "alice@example.com" },
  { $push: { hobbies: { $each: ["cooking", "hiking"] } } }
)

// $push with $each, $slice, $sort — keep only last 5 sorted items
db.users.updateOne(
  { email: "alice@example.com" },
  {
    $push: {
      recentViews: {
        $each: [{ productId: "p1", viewedAt: new Date() }],
        $slice: -5,
        $sort: { viewedAt: -1 }
      }
    }
  }
)

// $pop — remove first (-1) or last (1) element
db.users.updateOne({ email: "alice@example.com" }, { $pop: { hobbies: 1 } })   // remove last
db.users.updateOne({ email: "alice@example.com" }, { $pop: { hobbies: -1 } })  // remove first

// $pull — remove all elements matching a condition
db.users.updateOne(
  { email: "alice@example.com" },
  { $pull: { hobbies: "gaming" } }
)
db.orders.updateOne(
  { _id: ObjectId("...") },
  { $pull: { items: { qty: { $lt: 1 } } } }
)

// $addToSet — add only if value doesn't already exist (no duplicates)
db.users.updateOne(
  { email: "alice@example.com" },
  { $addToSet: { tags: "verified" } }
)

Upsert and arrayFilters

Upsert Option and arrayFilters
// upsert: true — insert if no document matches the filter
db.pageViews.updateOne(
  { page: "/home" },
  { $inc: { views: 1 }, $setOnInsert: { createdAt: new Date() } },
  { upsert: true }
)

// arrayFilters — update specific elements in nested arrays
// Update the qty of a specific item in an order's items array
db.orders.updateOne(
  { _id: ObjectId("...") },
  { $set: { "items.$[item].qty": 5 } },
  { arrayFilters: [{ "item.productId": "LAPTOP-001" }] }
)

// Update all array elements matching a condition
db.students.updateMany(
  {},
  { $set: { "grades.$[g].passed": true } },
  { arrayFilters: [{ "g.score": { $gte: 60 } }] }
)
Update Operators Quick Reference
// Field operators:
// $set         — set field value
// $unset       — remove field
// $inc         — increment/decrement
// $mul         — multiply
// $rename      — rename field
// $min         — update if new value is smaller
// $max         — update if new value is larger
// $currentDate — set to current date/timestamp
// $setOnInsert — set only on upsert insert

// Array operators:
// $push        — append to array
// $pop         — remove first/last element
// $pull        — remove matching elements
// $pullAll     — remove all listed values
// $addToSet    — add if not already present
// $each        — modifier for $push/$addToSet
// $slice       — modifier to limit array size
// $sort        — modifier to sort array elements
// $position    — modifier to insert at position

// Positional operators:
// $            — first matching element
// $[]          — all elements
// $[identifier] — filtered elements (with arrayFilters)

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.