Get items where the difference between sets is non-empty

Viewed 26

Given that I have an array ["a", "b", "c"], I would like to fetch all documents where any of the elements is not present in a field. For instance, if I have the item:

{
    a: ["a", "b"]
}

Since "c" is not present it should be retrieved but not:

{
    a: ["a", "b", "c"]
}

How would I make this query with MongoDB?

1 Answers

You can use $all to match all the elements in a, and $not for negative condition for $all operation,

collection.find({
  a: {
    $not: {
      $all: ["a", "b", "c"]
    }
  }
})

Playground

Related