0

I have a document that has a nested array that I need to add/remove items from. Normally you query a nested object by id but in this case a dynamic object _id wont work and I need to update by the nested profile id.

Document

{
    title: 'Title',
    members: [
      { 
          profile: { id: '123', name: 'Foo' },
          items: ['id1', 'id2', 'id3']
      }
    ]
}

Query

My thinking is I need some sort of $elemMatch & $pushAll combo but cant seem to get it working. For removing items from the array I would swap push for pull

await this.repo.findByIdAndUpdate(id, {
    members: {
        $elemMatch: { 'profile.id': '123' },
        $pushAll: {
            items: ['xxx', 'yyy'],
        },
    },
})

1 Answer 1

0

You need to use arrayFilters & $push with $each since $pushAll has been deprecated

db.collection.update({},
{
 $push: {
   "members.$[x].items": {
     $each: [
       "xxx",
       "yyy"
     ]
   }
 }
},
 {
  arrayFilters: [
    {
     "x.profile.id": "123"
    }
  ]
})

playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.