$inc — MongoDB Technical Interview Questions & Answers

Incrementing a numeric field by a given amount.

$inc

  • Simple meaning: $inc adds a number to a numeric field (can be negative).
  • How to use: db.students.updateOne({ roll: 12 }, { $inc: { marks: 5 } }) 72 becomes 77.
  • Try this: increment loginCount: 1 on a user doc.
  • Common mistake: $inc on a string field. $set when you meant “set to 5” not “add 5”.
  • Interview tip: Counters and scores — $inc is atomic on that document.

Technical Interview Tip: $inc for +1 counters. $set to assign an exact value.

Code Examples for $inc

$inc — working example

db.users.updateOne(
  { email: "ada@example.com" },
  { $inc: { loginCount: 1, score: 5 } }
)

$inc atomically increments (or decrements with a negative number) numeric fields.

How to Explain $inc to an Interviewer

What is $inc?

Atomically add to a number field { $inc: { marks: 5 } }