Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB update Nested field

Tags:

mongodb

set

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

like image 774
prit kalra Avatar asked Jun 12 '26 05:06

prit kalra


2 Answers

Thanks, but I found the solution :

db.collection.updateMany(
        { "address.street": "123" }, 
        { "$set": { "address.$[].street": "Main Street" } }
    )
like image 199
prit kalra Avatar answered Jun 14 '26 12:06

prit kalra


Use $set along with $ postion operator like this :

db.collection.update(
        { "address.street": "123" }, 
        { "$set": { "address.$.street": "Main Street" } }
    )
like image 22
Arbaz Siddiqui Avatar answered Jun 14 '26 12:06

Arbaz Siddiqui