In MongoDB how do you use $set to update a nested value/embedded document?

MongodbMongodb Query

Mongodb Problem Overview


In MongoDB how do you use $set to update a nested value?

For example, consider a collection people with the following document:

{
  _id: ObjectId("5a7e395e20a31e44e0e7e284"),
  name: "foo",
  address: { street: "123", town: "bar" }
}

How do I update the street field embedded in the address document from "123" to "Main Street"?

Mongodb Solutions


Solution 1 - Mongodb

Using the dot notation:

db.people.update({ }, { $set: { "address.street": "Main Street" } })

Solution 2 - Mongodb

In addition to Niels' answer, also do verify the "type" of the nested value. In my case, it was a "string" formed from json. Though this might be unlikely, but do ensure that the value has the right type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew LeSueurView Question on Stackoverflow
Solution 1 - MongodbNiels van der RestView Answer on Stackoverflow
Solution 2 - Mongodbuser2725012View Answer on Stackoverflow