In my mongodb aggregate pipeline I have a $facet
stage which produces multiple
output fields e.g.: pipe_1
and pipe_2
.
The result has the following form:
{
pipe_1: [{"key": "a"}, {"key": "b"}, {"key": "c"}, {"key": "d"}],
pipe_2: [{"key": "a"}, {"key": "B"}, {"key": "d"}]
}
My question is now, how do I get the following result from it:
[
{"key": "a"},
{"key": "d"}
]
I want only the keys, that are in both list and no duplicated should be in the result. Preferably I would like to have an answer without any slow group stages and it must work for more than two list.
Thank you in advance.
You can use $setIntersection operator:
db.collection.aggregate([
{
$project: {
result: {
$setIntersection: [ "$pipe_1", "$pipe_2" ]
}
}
}
])
Mongo Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With