Home > Blockchain >  How to check if an array contains exactly specific items independent of their order in MongoDB?
How to check if an array contains exactly specific items independent of their order in MongoDB?

Time:01-05

Every document has a users array. I want to check in db if a document has in its users array the value -> ['123','456'] OR ['456','123'], the order doesn't matter but I need that THESE AND ONLY THESE values are present in users array.

I'm basically looking for something like set(users.array) == set(456, 123)

I tried using $in operator but it is not working properly because it gives "true" if just one of these exists, and $all as I have seen don't check if these are the only values present.

CodePudding user response:

You will need to test 2 things:

  • the array contains all of the desired elements
  • the array does not contain any undesired elements

The $all query operator handles the first test. {$all: ["123","456"]}

For the second test, you can use then $nin operator, {$nin: ["123","456"]} Since that tests the entire array at once, by itself it will only match documents that don't contain the desired values.

Using the $elemMatch operator to apply the $nin test to each element separately matches unwanted documents. {$elemMatch:{$nin: ["123","456"}}

Invert the $eleMatch using $not to eliminate the undesired documents.

Putting that all together:

{$and: [
    {key: {$all: ["123","456"]}},
    {key: {$not: {$elemMatch: {$nin: {"123","456"}}}}}
]}

Playground

  • Related