lostintranslation
lostintranslation

Reputation: 24563

Mongo remove document if all elements in array match condition

Docs:

{
  _id: 1,
  items: [{thing: 5}, {thing: 7}]
}
{
  _id: 2,
  items: [{thing: 5}, {thing: 11}]
}

I would like to remove all docs from the collection above if all elements in array have "thing" < 10. IE for that case doc 1 should be removed, doc 2 should remain.

Is it possible with a query to find only docs where all elements in the array match with a $lt query?

I tried this:

db.mycollection.remove({items: {$all: [{$elemMatch: {thing: {$lt: 11}}}]}})

However that will remove all docs if any of the elements in the array match the condition.

Upvotes: 1

Views: 287

Answers (1)

Danny Varod
Danny Varod

Reputation: 18069

Use double negative (De-Morgan law):

{items: {$not: {$elemMatch: {thing: {$gte: 11}}}}}

Upvotes: 1

Related Questions