node.js - 使用 mongodb 汇总所有文档

标签 node.js mongodb sum aggregation-framework

我有一个包含三个文档的集合:

{ "_id" : ObjectId("5bfe572882ace71e43703d15"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "22000", "destination" : "98723546", "destinationcontext" : "from-internal", "callerid" : "\"22000\" <22000>", "channel" : "SIP/22000-00000005", "destinationchannel" : "SIP/9144502101-00000006", "lastapplication" : "Dial", "lastdata" : "SIP/9144502101/98723546,300,Tb(func-apply-sipheaders^s^1)", "starttime" : "2018-11-28 15:51:47", "answertime" : "", "endtime" : "2018-11-28 15:51:52", "duration" : "5", "billableseconds" : "0", "disposition" : "NO ANSWER", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395107.5", "userfield" : "" }
{ "_id" : ObjectId("5bfe5829b3a9321f241f10f2"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "98723546", "destination" : "s", "destinationcontext" : "ivr-1", "callerid" : "\"98723546\" <98723546>", "channel" : "SIP/9144502101-00000007", "destinationchannel" : "", "lastapplication" : "BackGround", "lastdata" : "custom/int1", "starttime" : "2018-11-28 15:56:03", "answertime" : "2018-11-28 15:56:03", "endtime" : "2018-11-28 15:56:09", "duration" : "6", "billableseconds" : "6", "disposition" : "ANSWERED", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395363.7", "userfield" : "" }
{ "_id" : ObjectId("5bfe5833b3a9321f241f10f4"), "event" : "Cdr", "privilege" : "cdr,all", "accountcode" : "", "source" : "98723546", "destination" : "22000", "destinationcontext" : "from-did-direct", "callerid" : "\"98723546\" <98723546>", "channel" : "SIP/9144502101-00000008", "destinationchannel" : "SIP/22000-00000009", "lastapplication" : "Dial", "lastdata" : "SIP/22000,,HhtrIb(func-apply-sipheaders^s^1)", "starttime" : "2018-11-28 15:56:12", "answertime" : "2018-11-28 15:56:12", "endtime" : "2018-11-28 15:56:19", "duration" : "7", "billableseconds" : "7", "disposition" : "NO ANSWER", "amaflags" : "DOCUMENTATION", "uniqueid" : "1543395372.8", "userfield" : "" }

我想计算 $duration 的总和并尝试命令:

db.cdrs.aggregate([{$group: { _id: "$event", total: { $sum: "$duration"}}}])

结果返回:

{ "_id" : "Cdr", "total" : 0 }

如何使用 $sum 返回结果三个文档的总持续时间(5 + 6 + 7 = 18)?

最佳答案

您可以通过将 string 转换为 Int求和 duration

Its work on Mongo version 4.0

示例:

db.getCollection('A').aggregate([{
    $addFields: {
      convertedDuration: { $toInt: "$duration" },
   } },
   {
    $group: { _id: "$event", total: { $sum: "$convertedDuration"} } 
   }
])

引用链接:link1 , link2

关于node.js - 使用 mongodb 汇总所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530754/

相关文章:

node.js - NPM 安装失败 - fsevents

php - 带有 MongoDB 子数组的 Codeigniter

javascript - 使用 Node js 中的 if 条件发布数据所需的逻辑(需要验证)

c++ - 从源构建 mongodb 时出错

javascript - 如何在nodejs中执行并行查询?

node.js - 如何使用 firebase-admin 删除数据?

mysql - 如何对表中每个唯一的最后一个值求和

一个大数的N个连续数字的Python总和

Mysql问题,根据where子句中提供的多个员工id对某些字段求和

linux - 如何杀死 "CLOSE_WAIT"和 "FIN_WAIT2"网络连接