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: "a",
address: [{ street: "123", town: "bar" }]
}
How do I update the street field embedded in the address document from "123" to "Main Street"?
Thanks, but I found the solution :
db.collection.updateMany(
{ "address.street": "123" },
{ "$set": { "address.$[].street": "Main Street" } }
)
Use $set along with $ postion operator like this :
db.collection.update(
{ "address.street": "123" },
{ "$set": { "address.$.street": "Main Street" } }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With