Update objects retaining or replacing separate entities

If you need to update a field in an object ensure reference is used correctly.

update a document like: db.movieDetails.updateOne({“title”:“The Martian”},{$set: {“awards”:{“wins”:8, “nominations”:14}}})
if then add a ‘text’ element with db.movieDetails.updateOne({“title”:“The Martian”},{$set: {“awards”:{“text”:“Nominated for 3 Golden Globes, another 8 wins and 14 nominations”}}})
it will replace the whole object and loose previous entries
use notation instead like: db.movieDetails.updateOne({“title”:“The Martian”},{$set: {“awards.text”:“Nominated for 3 Golden Globes, another 8 wins and 14 nominations”}})

Hi @mbunyan,

Thanks for sharing your learnings with the community :slight_smile: .

It happens because the $set operator is designed that way. It replaces the value of a field with the specified value.

To specify a <field> in an embedded document or in an array, we use dot notation which is exactly what you did in your last query.

For more information on this, please refer our documentation.

Happy Learning :slight_smile:

Thanks,
Shubham Ranjan
Curriculum Support Engineer

Hi everyone
I am following the M001 training course step by step. but I am facing problems with the UPDATE and $set operator, I had tried with the sintaxis describe on MongoDB document online, but the result is the same, I am attaching the exercise and shell results.

db.movieDetails.updateOne({“title”:“The Martian”},{$set: {“awards”:{“wins”:8, “nominations”:14}}})

{ “acknowledged” : true, “matchedCount” : 0, “modifiedCount” : 0 }

Make sure you are connected to your Sandbox cluster
Make sure you are in correct DB

It will be a good idea to run a find query to see if records exist or not before running the update

Please check all above.Your updateOne will work

HI @Marco_Antonio_91258,

As @Ramachandra_37567 mentioned, most likely you are not connected to the video database.

What’s the output of this command ?

db

~ Shubham