1

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?

1
  • See this Aggregation $group example, which has group by multiple fields (like your problem). Commented Oct 30, 2019 at 14:23

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

The last stage { $project: {_id: 0} } can be removed and the _id: 0 can be projected in the addFields stage itself..
@prasad_, it is 0.0 in this case if i put _id:0 at addfields level.
@MihirShah You are right. Replace $addFields and $project with this: { $project: { name : "$_id.name", value : "$_id.value", count: 1, _id: 0 } }.
@MihirShah Having extra stages can be sometimes a performance problem, especially if number of documents are large. So, its a just a good practice to avoid those always.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.