nerdexam
MongoDB

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

MongoDB Fundamentals

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)
  • A
    5% (3)
  • B
    3% (2)
  • C
    80% (51)
  • D
    13% (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 (a and b would remain), and _id is immutable so attempting to change it via $set throws an error.
  • B uses justOne: true, which is a valid option for remove(), not update() - passing it to update() 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 _id as 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

#update#document replacement#$set#$unset

Community Discussion

No community discussion yet for this question.

Full C100DBA Practice