Here\'s my MongoDB collection:
{
\"_id\" : ObjectId(\"515d8f53175b8ecb053425c2\"),
\"category\" : \"Batteries\",
\"products\" : [
{
After mongodb3.4, there is a $reduce
operator, so we can flat a array without extra stage.
1.
col.aggregate([
{
$project: {
items: {
$reduce: {
input: "$products.items",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] },
},
},
},
},
{ $unwind: "$items" },
{ $group: { _id: null, items: { $addToSet: "$items" } } },
]);
2.
col.aggregate([
{
$project: {
category: 1,
items: {
$setUnion: {
$reduce: {
input: "$products.items",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] },
},
},
},
},
},
]);