I’m looking for a solution since 3 hours and I don’t get it yet.
I have the following collection:
JavaScript
x
4
1
{text: 'random text 1', indexes:[1,2] },
2
{text: 'random text 2', indexes:[1,3] },
3
{text: 'random text 3', indexes:[2,4] },
4
and I would like to have only the documents that have all the index values in a given array like for example [1,2,4]
using the example above, I would like to have the following output:
JavaScript
1
3
1
{text: 'random text 1', indexes:[1,2] },
2
{text: 'random text 3', indexes:[2,4] },
3
[1,2]
is in [1,2,4]
-> OK
[1,3]
is not in [1,2,4]
because of 3 -> Not OK
[1,4]
is in [1,2,4]
-> OK
Any idea? thanks for your answer! 🙂
Advertisement
Answer
You can use one of this this $match
stage:
- Using $setIsSubset into
$expr
:
JavaScript
1
8
1
{
2
"$match": {
3
"$expr": {
4
"$setIsSubset": ["$indexes",[1,2,4]]
5
}
6
}
7
}
8
Example here
- Using
$elemMatch
and double negation ($not
and$nin
):
JavaScript
1
12
12
1
{
2
"$match": {
3
"indexes": {
4
"$not": {
5
"$elemMatch": {
6
"$nin": [1,2,4]
7
}
8
}
9
}
10
}
11
}
12
Example here