【问题标题】:How to take group using aggregrate in mongoDB?如何在 mongoDB 中使用聚合进行分组?
【发布时间】:2019-05-19 12:54:25
【问题描述】:

我正在尝试从这个 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

计算 Total Detections in Frame 的总和

我正在尝试这个

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

【问题讨论】:

    标签: mongodb grouping aggregate aggregate-functions


    【解决方案1】:

    你可以这样使用:

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

    【讨论】:

    • 感谢您的帮助,但它给出了这个错误 "assert: command failed: { "ok" : 0, "errmsg" : "Unrecognized expression '$toInt'", "code" : 168, “codeName”:“InvalidPipelineOperator”}:聚合失败_getErrorWithCode@src/mongo/shell/utils.js:25:13“
    • $toInt 与 $convert 一起添加到 Mongo 4.0 中,这就是您收到此错误的原因。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 2020-11-16
    • 2020-09-15
    • 2018-06-26
    • 2023-01-20
    • 2019-06-29
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多