C100DBA · Question #81
What does the following query do when performed on the posts collection? db.posts.update({_id:l},{Title:This is post with ID 1"})
The correct answer is B. Replaces the complete document with _id as 1 with the document specified in second parameter. In MongoDB's update() method, when the second parameter contains no update operators (like $set), MongoDB treats it as a replacement document - it discards all existing fields and replaces the entire matched document with the new one (preserving _id). That makes B correct: the do
Question
What does the following query do when performed on the posts collection? db.posts.update({_id:l},{Title:This is post with ID 1"})
Options
- ASyntax error
- BReplaces the complete document with _id as 1 with the document specified in second parameter
- CUpdates the Title of the post
- DUpdating a document is possible only with $set
How the community answered
(33 responses)- A3% (1)
- B85% (28)
- C9% (3)
- D3% (1)
Explanation
In MongoDB's update() method, when the second parameter contains no update operators (like $set), MongoDB treats it as a replacement document - it discards all existing fields and replaces the entire matched document with the new one (preserving _id). That makes B correct: the document with _id: 1 is fully replaced, not partially updated.
Why the distractors are wrong:
- A (Syntax error) - The query is syntactically valid MongoDB; it will execute without error.
- C (Updates the Title) - This is the most tempting wrong answer. Updating only a field requires
$set:{$set: {Title: "..."}}. Without$set, the entire document is replaced, so any other fields (e.g.,Body,Author) are lost. - D (Only $set can update) - False; MongoDB supports many update operators (
$inc,$unset,$push, etc.), and replacement-style updates (no operator) are also valid.
Memory tip: Think of the second parameter as two modes - operator mode (starts with $) modifies fields in place, while replacement mode (no $) swaps the whole document. If you don't see a $, the document gets replaced, not patched.
Topics
Community Discussion
No community discussion yet for this question.