如何在 mongoDB 中使用聚合进行分组?
Posted
技术标签:
【中文标题】如何在 mongoDB 中使用聚合进行分组?【英文标题】:How to take group using aggregrate in 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
【问题讨论】:
【参考方案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 中,这就是您收到此错误的原因。以上是关于如何在 mongoDB 中使用聚合进行分组?的主要内容,如果未能解决你的问题,请参考以下文章
如何对对象数据的mongodb聚合数组进行分组以对同一日期的数字求和
如何根据从 objectId 中提取的创建日期对 MongoDB 集合进行分组?