C100DBA · Question #121
Consider the following example document from the sample collection. All documents in this collection have the same schema. Which of the following queries will replace this with the document.
The correct answer is C. db.sample.update( { "_id" : 3 > , { "_id" : 7 , "c" : 4 , { "$unset" : [ "a" , "b" ] } } ). Option C is correct because it combines setting new field values (_id: 7, c: 4) with $unset to explicitly remove the old fields (a and b) that existed in the original document - this is the only approach that achieves a true document replacement by both adding new fields and elim
Question
Consider the following example document from the sample collection. All documents in this collection have the same schema. Which of the following queries will replace this with the document.
Options
- Adb.sample.update( { "_id" : 3 } , { "$set" : { "_id" : 7 , "c" : 4 > > )
- Bdb.sample.update( { "_id" : 3 > , { "_id" : 7 , "c" : 4 > , { "justOne" : true > ) / □This operation
- Cdb.sample.update( { "_id" : 3 > , { "_id" : 7 , "c" : 4 , { "$unset" : [ "a" , "b" ] } } )
- Ddb.sample.update( { "_id" : 3 > , { "_id" : 7 , "c" : 4 > )
How the community answered
(64 responses)- A5% (3)
- B3% (2)
- C80% (51)
- D13% (8)
Explanation
Option C is correct because it combines setting new field values (_id: 7, c: 4) with $unset to explicitly remove the old fields (a and b) that existed in the original document - this is the only approach that achieves a true document replacement by both adding new fields and eliminating old ones.
Why the others fail:
- A uses
$set, which only modifies specified fields without removing existing ones (aandbwould remain), and_idis immutable so attempting to change it via$setthrows an error. - B uses
justOne: true, which is a valid option forremove(), notupdate()- passing it toupdate()makes it an invalid operation. - D passes a plain replacement document
{_id: 7, c: 4}without operators, which would attempt to overwrite_id, but MongoDB treats_idas immutable and rejects any update that tries to change it.
Memory tip: Think of a document replacement as two-step housekeeping - you must bring in the new fields AND throw out the old ones. If you only bring in new data ($set) without throwing out old fields, the old fields linger. Option C is the only choice that does both.
Topics
Community Discussion
No community discussion yet for this question.