Here\'s my MongoDB collection:
{
\"_id\" : ObjectId(\"515d8f53175b8ecb053425c2\"),
\"category\" : \"Batteries\",
\"products\" : [
{
I am not sure what you all you have tried in the aggregation function but i thought unwind will help you to do the same , assuming you are not able to get it done , we have a map-reduce which will allow you to easily do this one . You can look into the http://docs.mongodb.org/manual/applications/map-reduce/ . It allow you to get the data in a manner you want and you can easily get the list . I think $unwind on the tags column and then $group them will always give the us the list of distinct tags as required by you in 1 and for 2nd case create $group on two key category and item which was $unwind earlier.
I know it is an old question and you've solved it several years ago! But there is a small problem in the answer you've marked as correct and it may not suitable for all cases. The $unwind
is an expensive operator and may affect latency and memory consumption for large datasets. I think the $reduce
operator is more performant in this case.
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"] },
},
},
},
},
},
]);
After few more tries, I had solved this. Here's the commands:
db.xyz.aggregate( {$project: {a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: 'a', items: {$addToSet: '$a'}}});
and
db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}},
{$unwind: '$a'},
{$unwind: '$a'},
{$group: {_id: '$category', items: {$addToSet: '$a'}}});