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

2019-01-12 02:25发布

问题:

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"?

回答1:

Using the dot notation:

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


回答2:

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.