Suppose I have an aggregate pipeline which returns the following set of documents:
[
{ "_id": 0, "refs": [1, 2] },
{ "_id": 1, "refs": [2, 3] }
]
How do I extend the aggregate pipeline to
- collect the set of distinct values in
"refs"
(i.e.[1, 2, 3]
) and - return the documents with
_id
matching the values in that set (i.e. 3 documents with_id
1, 2, and 3).
2
Answers
One option is to add 4 steps to your aggregation:
$group
in order to collect all refs$reduce
with$setUnion
in order to get the distinct values.$lookup
in order to get the docs from therefs
See how it works on the playground example
There are lots of ways to do this. Here’s another way.
Try it on mongoplayground.net.