I have a mongo collection with documents containing arrays:
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
I would like to get a single array containing all distinct values, such as:
tags: ["blank", "red", blue"] and dim_cm: [14,21,22.85,30,10,15.25]
Is this possible with an aggregation pipeline?
2
Answers
You can use
$group
with$reduce
and$setIntersection
:$group
all documents to create one array of arrays per key$reduce
and make it a set using$setIntersection
.See how it works on the playground example
Another way is:
Playground – unwind
Which you can split into two queries which will be much faster:
A 3rd option is:
Playground 3rd
Query
*here types are different, in case they were the same type, we can do another trick like put the in an array of pairs
[[tag,cm] ...]
where first would be the tag and the second would be the cm, or array of documentsFor perfomance if you test it send how it went if you can
Playmongo