0

I have a collection looking like this:

{
    "_id" : 1,
    "category" : [
         {
           "name": "category1"
         },
         {
           "name": "category2"
         }
    ],
    "event": [
               {
                 type: "house"
               },
               {
                 type: "mouse"
               }
             ]
},

{
    "_id" : 2,
    "category" : [
         {
           "name": "category2"
         },
         {
           "name": "category3"
         }
    ]
},

{
    "_id" : 3,
    "category" : [
         {
           "name": "category3"
         },
         {
           "name": "category1"
         }
    ],
        "event": [
           {
             type: "mouse"
           }
         ]
}

I need to do a group by distinct category name types and count if an event exists to get a document like:

{ "category1": total_count: 2,
  "category2": total_count: 0,
  "category3": total_count: 1}

Any help would be highly appreciated.

2
  • You should use the aggregation pipeline. Did you try that? Commented Jul 20, 2017 at 16:53
  • yes, but without success.. it would work if category isn't an array, but i don't know how to "explode" the array first and then group it by distinct values of them Commented Jul 21, 2017 at 8:15

1 Answer 1

2

Try this, it works for me:

db.getCollection('coll').aggregate([
{$unwind: "$category"},
{$group :{
    _id : "$category.name",   
    total_count : {$sum : 1}
 }
}]) 
Sign up to request clarification or add additional context in comments.

2 Comments

unwind! that's it
@Codutie yep :)

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.