1

I am struggling to find the format for a query to remove an element (with an _id) from an array of arrays in Mongo.

When looking at the docs I couldn't find anything that was similar to what I have https://www.mongodb.com/docs/manual/reference/operator/update/pull/#up._S_pull

I know: the _id of the document in MySchema and the _id of the array element in innerArray.

I don't know the outerArray _id

Could someone help point out where I went wrong Thank you!

This is an example of the data (imagine the _id in ObjectId)

{
  outerArray:[
           {
             _id: 1
             innerArray: [{_id: 23, name: '123'}, {_id: 13, name: 'asdac'} ] 
           },
           {
             _id: 2,
             innerArray: [{_id: 16,name:'asf' }, {_id: 18,name:'asf' } ] 
           },
           {
            _id: 3,
            innerArray: [{_id: 136,name:'asf' }, {_id: 128,name:'asf' } ] 
           }
          ]
}

innerIds is an array of mongoose.Types.ObjectId

return MySchema.updateOne(
    {
      _id: documentId,
    },
    { $pull: { outerArray: { innerArray: { _id: { $in: innerIds } } } } },
  )
    .session(session)
    .exec()
3
  • Cast to ObjectId failed for value "{ '$in': [ 6284f3ce02e46e57fcc32e98, 6284f3c902e46e57fcc32e28 ] }" (type Object) at path "_id" Commented May 18, 2022 at 15:52
  • that's what the error message for that one says Commented May 18, 2022 at 15:53
  • { $pull: { 'outerArray.$. innerArray._id': { $in: innerIds } } } Tried this and got this "The positional operator did not find the match needed from the query." Commented May 18, 2022 at 15:54

1 Answer 1

1
db.collection.update({},
{
  $pull: {
    "outerArray.$[].innerArray": {//$[] does the trick
      _id: {
        $in: [
          16
        ]
      }
    }
  }
})

playground

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

1 Comment

Reference helps to update arrays that contains embedded documents. It is different from $

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.