Matthias Herrmann
Matthias Herrmann

Reputation: 2790

Mongodb Aggregate Using Group And Getting Count Of Properties Which Equal Condition

I'm trying to implement the following query as efficient as possible so I'm using the Mongodb Aggregation framework.

I have a collection called mydevices which contains documents each representing a device of the following format:

{
  BUILDING: 'stringValue',
  DEVICECLASS: 'stringValue',
}

The output which I'm trying to achieve is an array for each BUILDING containing the count of devices per DEVICECLASS in each category e.g.

'building xy': {
   'mobile phone': 5,
   'destkop': 3
}

What I have tried so far:

  collection.aggregate(
        [
            {
                $group:{ // group by building
                    _id: {BUILDING},
                    DEVCLASS: {DEVCLASS} // save devclass as property
                }
            }
        ]
    )

It seems like the $count operator is not helpfull in my case?

$count Returns a document that contains a count of the number of documents input to the stage.

I have read the documentation but I'm stuck now. How can I achieve the result?

Upvotes: 0

Views: 1191

Answers (1)

Kinjal Patel
Kinjal Patel

Reputation: 61

Try:

collection.aggregate([{$group:{_id:{"building" : "$building", "deviceclass":"$deviceclass"},count:{$sum:1} }},
       {$group:{_id:{"building" : "$_id.building" },result : {$push : {"deviceclass" : "$_id.deviceclass","count" : "$count"}}}},
        {$project : {"building" : "$_id.building" , "deviceclass" : "$result",_id:0}}
    ])  

You will get:

{
    "building" : "building xy",
    "deviceclass" : [ 
        {
            "deviceclass" : "mobile phone",
            "count" : 2.0
        }, 
        {
            "deviceclass" : "destkop",
            "count" : 1.0
        }
    ] 
}

Upvotes: 1

Related Questions