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"
?
Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
Using the dot notation:
db.people.update({ }, { $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