简体   繁体   中英

MongoDB: updating 2 arrays in the same document

User:

{
_id: "userID",
array_1:[],
array_2:[]
}

I need to do two updates to this document:

  1. array_1 contains objects with unique id property. I need to find one where id=targetID and replace it with the newObject , like this:
User.updateOne(
    {
      _id: userID, 
      "array_1.id": targetID
    }, 
     {
       "$set":{"array_1.$":newObject}
     }
  )
  1. array_2 contains objects, where multiple objects can have same id values. I need to update 2 properties of all objects in the array_2 where id=targetID , like this:
User.updateOne(
  { 
    _id: userID, 
    "array_2.id": targetID
  },
  { 
    "$set": { 
              "array_2.$[elem].property_1": new_property_1, 
              "array_2.$[elem].property_2": new_property_2 
            } 
  },
  { 
    "arrayFilters": [{ "elem.id": targetID }], 
    "multi": true 
  }
  )

These two work fine if I run it separately, but how do I combine both in one function?

You can combine it using arrayFilters, same as you did nin second query,

  • create a filters property arr1 and use it to update object,
await User.updateOne(
  { _id: userID },
  {
    $set: {
      "array_1.$[arr1]": newObject,
      "array_2.$[elem].property_1": new_property_1,
      "array_2.$[elem].property_2": new_property_2
    }
  },
  {
    arrayFilters: [
      { "elem.id": targetID },
      { "arr1._id": targetID }
    ]
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM