如何在mongoDB中使用aggregrate进行分组?

时间:2018-12-19 03:49:19

标签: mongodb grouping aggregate aggregate-functions

我正在尝试根据BSON数据对一些元素进行分组

 {
    "_id" : ObjectId("5c18e25926fb081b8b5b0240"),
    "Total Detections in Frame" : "2",
    "StoreName" : "BH",
    "FPS" : "0.033",
    "Video Duration" : "3599",
    "ToTime" : "13",
    "Date" : "16-12-2018",
    "FromTime" : "12",
    "Frame Number" : "97"
}
{
    "_id" : ObjectId("5c18e29326fb081bc5339277"),
    "Total Detections in Frame" : "2",
    "StoreName" : "BH",
    "FPS" : "0.033",
    "Video Duration" : "3599",
    "ToTime" : "13",
    "Date" : "16-12-2018",
    "FromTime" : "12",
    "Frame Number" : "97"
}
{
    "_id" : ObjectId("5c18e29326fb081bc5339278"),
    "Total Detections in Frame" : "4",
    "StoreName" : "ME",
    "FPS" : "0.033",
    "Video Duration" : "3599",
    "ToTime" : "15",
    "Date" : "16-12-2018",
    "FromTime" : "14",
    "Frame Number" : "6"
}
{
    "_id" : ObjectId("5c18e29326fb081bc5339279"),
    "Total Detections in Frame" : "2",
    "StoreName" : "ME",
    "FPS" : "0.033",
    "Video Duration" : "3599",
    "ToTime" : "11",
    "Date" : "16-12-2018",
    "FromTime" : "10",
    "Frame Number" : "54"
}

现在,我要根据 StoreName

帧中的总检测次数进行求和

我正在尝试

  

{db.generico_new.aggregate([{“ $ group”:{_id:“ $ StoreName”,count:{$ sum:1}}}])

其结果是

{ "_id" : "GH", "count" : 1209 }
{ "_id" : "MW", "count" : 1203 }
{ "_id" : "ME", "count" : 1443 }
{ "_id" : "BH", "count" : 1460 }

这给出了由相应storeName键显示的全部文档数,现在我如何获得类似这样的结果

{ "_id" : "GH", "Total Detections in Frame" : Some Number }
{ "_id" : "MW", "Total Detections in Frame" : Some Number }
{ "_id" : "ME", "Total Detections in Frame" : Some Number }
{ "_id" : "BH", "Total Detections in Frame" : Some Number }

1 个答案:

答案 0 :(得分:1)

您可以这样使用:

db.collection.aggregate([
  {
    $group: {
      _id: "$StoreName",
      "Total Detections in Frame": {
        $sum: {
          $toInt: "$Total Detections in Frame"
        }
      }
    }
  }
])