Home > Enterprise >  How to update multiple properties of a nested object inside an array in Mongodb?
How to update multiple properties of a nested object inside an array in Mongodb?

Time:09-29

Let say we have a document in mongodb

{
  id : 101,
  addresses : [
    {
      id: 1,
      suite: "flat 201",
      street: "north street"
      city: "london",
      country: "uk"
    }
  ]
}

i want to update multiple properties of the object at once without replacing whole object. For example :

const newAddress = {
  id:1,
  suite: "flat 301",
  street: "south street"
} 


userCollection.updateOne(
  {id : 101},
  { $set : {"addresses.$[address]" : newAddress } },
  {arrayFilters: [{address.id : newAddress.id}]}
)

This operation sets the object with new fields instead of updating only the given fields.

CodePudding user response:

When you update an object's properties, it must be required to specify each one by one, and if the properties are dynamic then you have to prepare a payload for an update on client side,

I assume you are using javascript,

const newAddress = {
  id:1,
  suite: "flat 301",
  street: "south street"
};

let set = {};
for (let n in newAddress) {
  set["addresses.$[address]." n] = newAddress[n];
}

console.log(set);

// prepared update object
{
 "addresses.$[address].id": 1,
 "addresses.$[address].suite": "flat 301",
 "addresses.$[address].street": "south street"
}

You can pass set to update part in query,

userCollection.updateOne(
  { id : 101 },
  { $set : set },
  { arrayFilters: [{ "address.id" : newAddress.id }] }
)

You can do this directly in an update query but you have to use an update with an aggregation pipeline and I don't recommend this because it requires multiple expression operators and it is expensive.

  • Related