Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 213
Drew LeSueur Avatar asked Sep 30 '10 06:09

Drew LeSueur


People also ask

How do I update a nested array in MongoDB?

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.

How do I update nested objects?

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.

How do I query a nested document in MongoDB?

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.


1 Answers

Using the dot notation:

db.people.update({ }, { $set: { "address.street": "Main Street" } }) 
like image 144
Niels van der Rest Avatar answered Oct 12 '22 06:10

Niels van der Rest