簡體   English   中英

用mongodb對所有文檔求和

[英]Sum all document with mongodb

我有一個包含三個文檔的集合:

{ "_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 ,我想mongoDB不會轉換和求和,請在存儲時將持續時間更改為Number。 您的查詢很好。

您可以通過將string轉換為Intsum duration

它在Mongo version 4.0上的工作

范例:

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

參考鏈接: link1link2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM