Mihir Shah
Mihir Shah

Reputation: 1809

Mongodb nested array group with key value array count

I have mongodb structure like below:

{
"_id":"123456789",
"name":"item name 1",
"variants":[
    {
    "size":"150 ml",
    "filters":[

    {"name":"filter 1",
    "value":"value 1"},
    {"name":"filter 2",
     "value":"value 2"}
  ]
   } 
]
},

{
"_id":"987654321",
"name":"item name 1",
"variants":[
    {
    "size":"200 ml",
    "filters":[

    {"name":"filter 1",
    "value":"value 2"},
    {"name":"filter 2",
     "value":"value 1"}
  ]
   } 
]
}

Now i want count of filter with group by name and value. i.e.

[{filter 1:[{value:value 1, count:10}, {value: value 2, count:5}]},
{filter 2:[{value:value 1, count:5}, {value: value 2, count:2}]}

or

  [{name:filter 1, value:value 1, count:10}, {name:filter 1, value:value 2, 
count:5}]

how to achieve this using mongodb aggregrate and group query?

Upvotes: 1

Views: 231

Answers (1)

Haruo
Haruo

Reputation: 516

You can try this Way:

db.collection.aggregate([
    { $unwind: "$variants" },
    { $unwind: "$variants.filters" },
    { $group:
        {
            _id: "$variants.filters",
            count:{$sum:1}
        }
    },
    { $addFields: {"name" : "$_id.name", "value" : "$_id.value"}},
    { $project: {_id: 0} }
]);

A working example at https://mongoplayground.net/p/an2xVfDusJn.

Upvotes: 3

Related Questions