fatiherdem
fatiherdem

Reputation: 1223

MongoDB Aggreation Multiple Group

I have millions of records like this:

{
    "_id" : ObjectId("568adba57faad8f22ff38a07"),
    "temperature" : 27,
    "elapsedTime" : 27,
    "stationId" : 28,
    "beaconId" : 238,
    "beaconClass" : 1,
    "batteryLevel" : 61
}

I want to group my records like this:

{"stationId":1, "beaconClass":1, total_time: summary_of_elapsedTime_in_station_for_this_beaconClass}
{"stationId":1, "beaconClass":2, total_time: summary_of_elapsedTime_in_station_for_this_beaconClass}
...
...
{"stationId":2, "beaconClass":1, total_time: summary_of_elapsedTime_in_station_for_this_beaconClass}
{"stationId":2, "beaconClass":2, total_time: summary_of_elapsedTime_in_station_for_this_beaconClass}
{"stationId":2, "beaconClass":3, total_time: summary_of_elapsedTime_in_station_for_this_beaconClass}
...
...
// so on

I can group by stationId or beaconId or class. But when I try to group by multiple column getting error.

How can I create aggregation query for this?

Upvotes: 0

Views: 1418

Answers (1)

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

For grouping on several fields you need to specify an aggregate key for the _id value. Take a look at the $group documentation.

Try the following query:

db.collection.aggregate([
  {  
    $group: {
      _id: {stationId: "$stationId", beaconClass: "$beaconClass"}, 
      elapsedTime: {$sum: "$elapsedTime"}
    } 
  }
])

If you need to project the received fields to another schema you can take advantage of $project operator in the aggregation:

{
    $project: { _id: 0, stationId: "$_id.stationId", beaconClass: "$_id.beaconClass", elapsedTime: 1 } 
} 

Upvotes: 2

Related Questions