1

I'm trying to execute a query which remove some specific elements which match at least one condition from a set of conditions,

{
    id: 'myId',
    path2: [{
        a: '1'
    },{
        a: '2'
    },{
        a: '3'
    }]
}

and update it to:

{
    id: 'myId',
    path2: [{
        a: '1'
    }]
}

Here, I removed from path2 all elements where the value of the 'a' field is equal to either 2 or 3.

I tried the following with no success (I'm using mongoose):

let conditions = ['2', '3'];

myModel.findOneAndUpdate({id: 'myId'},
    {$pull: {path2: {$elemMatch: {a: {$in: conditions}}}}}
);

Thank you in advance.

Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30
masterbate
  • 19
  • 1
  • 7
  • Try `let conditions = ['2','3']; myModel.findOneAndUpdate({id: 'myId'}, {$pull:{path2: {a: {$in:conditions}}}});` – s7vr Jan 27 '18 at 17:54
  • Possible duplicate of [How to remove array element in mongodb?](https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) – s7vr Jan 27 '18 at 17:56
  • Thank you Veeram! it works nice :) . It's is not a duplicate question as i'm trying to find all values which fullfill a set of conditions and not only one condition as it is shown in the question you indicate – masterbate Jan 27 '18 at 18:13

1 Answers1

0

This should do,

myModel.findOneAndUpdate({id: 'myId'}, {$pull: {path2: {a: {$in: conditions}}}} );

You don't need to use elemMatch.

Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30