Mongodb Certified Developer Associate C100dev · Free Practice Question Medium
Question 17
You are working with a profiles collection that stores documents in the following structure:
- {
- "_id": ObjectId("..."),
- "username": "tech_guru",
- "loginCount": 4,
- "settings": {
- "theme": "light",
- "notifications": true
- }
- }
You need to increment the loginCount by 1 only if notifications is currently set to true. Which of the following update operations correctly implements this logic?
-
A
- db.profiles.updateOne(
- { "settings.notifications": true },
- { $set: { loginCount: loginCount + 1 } }
- )
-
B
- db.profiles.updateOne(
- { loginCount: { $exists: true } },
- { $inc: { "settings.notifications": 1 } }
- )
-
C
- db.profiles.updateOne(
- { loginCount: { $gte: 0 } },
- { $push: { loginCount: 1 } }
- )
-
D
- db.profiles.updateOne(
- { "settings.notifications": true },
- { $inc: { loginCount: 1 } }
- )
Reveal correct answer
Correct answer: D
A.
JavaScript syntax like loginCount + 1 cannot be used directly in an update expression. MongoDB does not interpret this syntax — you must use update operators like $inc.
B.
This query matches any document with a loginCount field, and tries to increment a Boolean field (settings.notifications), which is invalid and would cause an error.
C.
$push is used to add elements to an array. Since loginCount is a numeric field, using $push here would cause an error or undesired type coercion.
D.
This uses a query filter that matches only documents with settings.notifications equal to true. The $inc operator then increments the loginCount field. This is the correct and idiomatic approach.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
