Tutorials Logic, IN info@tutorialslogic.com

MongoDB Update Operators $set, $push, $inc: Tutorial, Examples, FAQs & Interview Tips

MongoDB Update Operators $set, $push, $inc

MongoDB in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

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, $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, $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 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

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)

Applied guide for MongoDB

Use MongoDB when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why MongoDB is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.

  • Identify the exact problem solved by MongoDB.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.
Key Takeaways
  • I can explain where MongoDB fits inside a product catalog or user activity store.
  • I can point to the exact document shape and index affected by this topic.
  • I tested a normal case and an edge case involving missing, repeated, empty, or boundary input.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small collection query that demonstrates MongoDB in a product catalog or user activity store.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.

Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.

Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

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