Home > Net >  Mongodb - Get record that match exactly an array but regardless of the order of elements in the arra
Mongodb - Get record that match exactly an array but regardless of the order of elements in the arra

Time:03-22

I have a column like

A.  'col' : [
            '5ed3ede8844f0f351100000c',
            '5ed3f117a844e0471100000d'
    ]

or some other case data

B.   'col' : [
            '5ed3ede8844f0f351100000c'
     ]

C.   'col' : [
            '5ed3ede8844f0f351100000c',
            '5ed3f117a844e0471100000d',
            '5ed3f18132f50c491100000e'
     ]

How to get A record that match exactly an array but regardless of the order of elements in the array with one query

Example

.find({'col': ['5ed3ede8844f0f351100000c','5ed3f117a844e0471100000d']})

or .find({'col': ['5ed3f117a844e0471100000d', '5ed3ede8844f0f351100000c']})

How to do that thanks

CodePudding user response:

In order to find a record that match exactly a specified array without taking into consideration the order of the elements within the array, you can combine the $size and the $all query operators.

So for example:

.find({ 'col': { "$size": 2, "$all": ['5ed3f117a844e0471100000d', '5ed3ede8844f0f351100000c'] } })

Note: you can also use the $in query operator, but for your case it looks like the $all is a better fit

  • Related