In MongoDB how do you use $set to update a nested value/embedded document?
-
26-09-2019 - |
문제
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"
?
해결책
Using the dot notation:
db.people.update({ }, { $set: { "address.street": "Main Street" } })
다른 팁
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.
제휴하지 않습니다 StackOverflow