The $inc operator is used to add or subtract a number from a field's current value in a document. It helps update numbers easily without replacing the whole value.
$inc operator for incrementing in MongoDB
Start learning this pattern below
Jump into concepts and practice - no test required
db.collection.updateOne(
{ <filter> },
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
)The $inc operator takes an object where keys are field names and values are numbers to add (positive) or subtract (negative).
If the field does not exist, $inc will create it and set it to the increment value.
db.users.updateOne({ name: "Alice" }, { $inc: { score: 5 } })db.products.updateOne({ item: "Pen" }, { $inc: { stock: -3 } })db.counters.updateOne({ _id: "pageViews" }, { $inc: { count: 1 } })This example first adds a document with 10 notebooks. Then it increases the quantity by 5 using $inc. Finally, it shows the updated document.
db.inventory.insertOne({ item: "notebook", qty: 10 })
db.inventory.updateOne({ item: "notebook" }, { $inc: { qty: 5 } })
db.inventory.find({ item: "notebook" }).toArray()You can increment multiple fields at once by listing them inside the $inc object.
Using a negative number with $inc subtracts from the field.
If the field is not a number, $inc will cause an error.
$inc updates numeric fields by adding or subtracting values.
It creates the field if it does not exist.
Use it to change numbers without replacing the whole document.
Practice
$inc operator do in MongoDB?Solution
Step 1: Understand the purpose of
The$inc$incoperator is used to add or subtract a number from an existing numeric field in a document.Step 2: Compare with other options
Replacing documents, deleting fields, or creating collections are not functions of$inc.Final Answer:
It increments or decrements the value of a numeric field. -> Option BQuick Check:
$incchanges numbers by adding/subtracting [OK]
$inc changes numbers, not documents [OK]- Thinking
$increplaces the whole document - Confusing
$incwith delete or create operations - Assuming
$incworks on non-numeric fields
score by 5 in MongoDB?Solution
Step 1: Check the value type for
The value to increment must be a number, not a string or word.$incStep 2: Validate syntax correctness
{ $inc: { score: 5 } } uses a number 5 correctly. { $inc: { score: '5' } } uses a string '5', which is invalid. { $inc: { 'score': 'five' } } uses a word 'five', invalid. { $inc: { score: '+5' } } uses a string '+5', invalid.Final Answer:
{ $inc: { score: 5 } } -> Option DQuick Check:
Use number values with$inc[OK]
$inc [OK]- Using strings instead of numbers for increment values
- Adding plus sign (+) inside JSON value
- Using words instead of numeric literals
{ _id: 1, count: 10 }, what will be the document after running db.collection.updateOne({ _id: 1 }, { $inc: { count: -3 } })?Solution
Step 1: Understand the initial document
The document hascountequal to 10.Step 2: Apply the
Subtract 3 from 10: 10 - 3 = 7.$incoperation with -3Final Answer:
{ _id: 1, count: 7 } -> Option CQuick Check:
10 + (-3) = 7 [OK]
$inc [OK]- Adding instead of subtracting when using negative values
- Replacing the whole document instead of updating
- Assuming
$inconly increments, not decrements
db.collection.updateOne({ _id: 2 }, { $inc: { visits: 1 } }) but get an error. What is the most likely cause?Solution
Step 1: Understand
$increquirements$inconly works on numeric fields. Ifvisitsis a string, it causes an error.Step 2: Check other options
Missing_idwould not cause this error if the document exists.$inccan increment by 1. Collection existence error would be different.Final Answer:
Thevisitsfield is a string, not a number. -> Option AQuick Check:
$incneeds numeric fields [OK]
$inc [OK]- Trying to increment string fields
- Assuming
$incworks on any data type - Ignoring error messages about field types
likes field by 1 for all documents where likes does not exist yet. Which update command will correctly do this without errors?Solution
Step 1: Identify documents without
Use the querylikes{ likes: { $exists: false } }to find documents missing thelikesfield.Step 2: Use
$incto add 1 tolikes$incwill create the field with value 1 if it does not exist, so this safely increments missing fields.Step 3: Check other options
db.collection.updateMany({}, { $inc: { likes: 1 } }) increments all documents, including those withlikes. db.collection.updateMany({ likes: null }, { $inc: { likes: 1 } }) matches documents wherelikesis null, not missing. db.collection.updateMany({}, { $set: { likes: 1 } }) setslikesto 1, not increments.Final Answer:
db.collection.updateMany({ likes: { $exists: false } }, { $inc: { likes: 1 } }) -> Option AQuick Check:
Increment missing fields with$exists: falsefilter [OK]
$exists: false before $inc [OK]- Incrementing all documents without filtering
- Using
$setinstead of$inc - Filtering with
nullinstead of$exists: false
