Let say I have those document like bellow
[
{
array : ['a', 'b' , 'c'],
},
{
array : ['b', 'd' , 'e'],
},
{
array : ['d', 'e' , 'f'],
},
]
and input array for query
["b","d","e","f"]
expect output :
['b', 'd' , 'e'],['d', 'e' , 'f']
Which query can I use to do that?
And how to filter which element is not in the document?
expect :
[
{
array : ['b', 'd' , 'e'],
missingElement : ['f']
},{
array : ['d', 'e' , 'f'],
missingElement : ['b']
},
]
>Solution :
-
$expr– Allow to use aggregation operator.1.1.
$eq– Compare the result from 1.1.1 and 1.1.2 are equal.1.1.1.
$size– Get the size ofarrayfield.1.1.2.
$size– Get the size of array from the result 1.1.2.1.1.1.2.1.
$setIntersection– Intersectarrayfield and input array, return the intersected value(s) in array.
db.collection.find({
$expr: {
$eq: [
{
$size: "$array"
},
{
$size: {
$setIntersection: [
"$array",
[
"b",
"d",
"e",
"f"
]
]
}
}
]
}
})