MongoDB Aggreation Multiple Group

时间:2016-01-09 16:14:05

标签: mongodb mongodb-query aggregation-framework

我有数以百万计的记录:

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

我想像这样分组我的记录:

{"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

我可以通过stationId或beaconId或类进行分组。但是当我尝试按多列分组获取错误时。

如何为此创建聚合查询?

1 个答案:

答案 0 :(得分:2)

要对多个字段进行分组,您需要为_id值指定聚合键。看看$ group documentation

尝试以下查询:

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

如果您需要将收到的字段投影到另一个架构,您可以在聚合中利用$project运算符:

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