C100DBA · Question #102
Which option can be used with update command so that a new document gets created if no matching document is found based on the query condition?
The correct answer is D. Specify {upsert : true } as the third parameter of update command. Option D is correct because MongoDB's update() command accepts an options object as its third parameter, and setting { upsert: true } tells MongoDB to insert a new document if no existing document matches the query - combining "update" and "insert" into one atomic operation…
Question
Which option can be used with update command so that a new document gets created if no matching document is found based on the query condition?
Options
- Aupsert command instead of update command
- BThis has to be handled in application code (Node.js, PHP, JAVA, C#, etc.) and cannot be handled in
- C{update: true, insert: true} as the third parameter of update command
- DSpecify {upsert : true } as the third parameter of update command
How the community answered
(20 responses)- A5% (1)
- B10% (2)
- D85% (17)
Explanation
Option D is correct because MongoDB's update() command accepts an options object as its third parameter, and setting { upsert: true } tells MongoDB to insert a new document if no existing document matches the query - combining "update" and "insert" into one atomic operation.
Why the distractors are wrong:
- A is wrong because
upsertis not a separate command - it's an option within the update command, not a replacement for it. - B is wrong because MongoDB handles this natively at the database level; no application-side logic is needed.
- C is wrong because
{ update: true, insert: true }is not valid MongoDB syntax - the correct key isupsert, not separateupdate/insertflags.
Memory tip: Think of "upsert" as a portmanteau of UPdate + inSERT - it does both in one step. The option lives in the third parameter (after the query and update document), just like other behavioral flags such as multi.
Topics
Community Discussion
No community discussion yet for this question.