Question on Chapter 3 Quiz: Updating Documents in the shell

I have understand the lecture video and read about the documentation for Set and Push with update.

Here is my understanding:
Set: Update the existing field in the collection with the same id.
Push: Add new field to exsting collection with the same id.

The question:

{
“_id”: ObjectId(“5ec414e5e722bb1f65a25451”),
“pet”: “wolf”,
“domestic?”: false,
“diet”: “carnivorous”,
“climate”: [“polar”, “equatorial”, “continental”, “mountain”]
}

Here is my doubt:

db.pets.updateMany({ “pet”: “cat” },
{ “$push”: { “climate”: “continental”,
“look”: “adorable” } })

The “look” field is new to the collection with id “5ec414e5e722bb1f65a25451”. Why Push is allow to use but “climate” is not new thus why it is allow to use Push?

db.pets.updateMany({ “pet”: “cat” },
{ “$set”: { “type”: “dangerous”,
“look”: “adorable” }})

“type” and “look” fields are new why we can use set instead of push?

For the 2 options that are incorrect:

db.pets.updateMany({ “pet”: “cat” },
{ “$set”: { “climate”: “continental” }})

db.pets.updateMany({ “pet”: “cat” },
{"$set": { “domestic?”: true, “diet”: “mice” }})

The explanation given is that it will update the exiting value in the array to single value as of the incorrect options. However, the “pet” field are not “wolf” (refer to the question), how can the code change the whole thing instead of adding a new set of data into the collection?

Starts from you understanding:

Set: Update/Add or do both in the existing document.

Push: Same function as “set” operator but when there is an array field.

From above you can see the difference.

And for the last part where field is “pet”: “wolf” in the given question.

Because this is pets collection. That is why question is showing a single document so we can see what is inside, and we are updating those documents where pet field have cat value.

Hope this helps. Thanks :smiley:

2 Likes