• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

13
Views
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?

7 days ago ·

Santiago Trujillo

1 answers
Answer question

0

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 }
    ]
  }
)
7 days ago · Santiago Trujillo Report
Answer question
Remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Startups
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.