MongoDB攻击多组

MongoDB攻击多组,mongodb,mongodb-query,aggregation-framework,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

我有数百万张这样的唱片:

{
    "_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
我想将我的记录分组如下:

{
    "_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或class进行分组。但当我尝试按多个列分组时,出现了错误


如何为此创建聚合查询?

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

请尝试以下查询:

db.collection.aggregate([
  {  
    $group: {
      _id: {stationId: "$stationId", beaconClass: "$beaconClass"}, 
      elapsedTime: {$sum: "$elapsedTime"}
    } 
  }
])
如果需要将收到的字段投影到另一个架构,可以利用聚合中的运算符:

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

它起作用了!真不敢相信这么简单。谢谢。你能给我解释一下为什么我们没有使用多个
$group
键吗?它怎么能处理得这么简单呢?不要从下面的查询开始回答问题,而是试着解释一下你的查询在做什么以及它为什么工作。此外,您不需要在此处使用
$project
阶段,因为它会导致性能下降