2015-02-10 154 views
-1

我想從MongoDB表中創建一些日常統計數據。該文檔包含具有創建日期,狀態(警告,錯誤,完成)的消息。我想產生一個查詢,每個記錄的結果爲 - 日期,計數警告,錯誤計數,計數完成。我是Mongo的新手,只是學習查詢語言。我試過,結果好壞參半聚集:MongoDB中的聚合查詢

db.TransactionLogs.aggregate(
{ $group : { 
     _id : { 
     category: {$substr:["$startDate",0,10]}, 
     term: "$Status", 
     }, 
     total: { $sum : 2 } 
    } 
}) 

導致每日期多個記錄的狀態:

"result" : [ 
     { 
      "_id" : { 
       "category" : "2015-02-10", 
       "term" : "Completed", 
      }, 
      "total" : 532 
     }, 
     { 
      "_id" : { 
       "category" : "2015-02-10", 
       "term" : "Error", 
      }, 
      "total" : 616 
     }, 

消息:

{ "_id" : "2ceda481-3dd3-480d-800d-95288edce6f2", "MID" : "02de5194-7a1d-4854-922c-934902840136", "Status" : "Completed", "firstName" : "Willy", "lastName" : "Wire", "allocation" : "100", "initEvent" : "Marriage", "system" : "Oracle", "startDate" : "2015-02-06T19:03:34.237Z", "stopDate" : "2015-02-06T19:23:34.237Z", "plan" : "445-A" } 

我敢肯定,它的缺乏瞭解我的聚合。任何幫助或方向非常感謝!

我想通了。我需要看看如何在Mongo中「支點」。這工作:

db.TransactionLogs.aggregate([ { $project: { startdate: {$substr:["$startDate",0,10]}, 
        cnt_e1: { $cond: [ { $eq: [ "$Status", "Error" ] }, "$count", 1 ] }, 
        cnt_e2: { $cond: [ { $eq: [ "$Status", "Warning" ] }, "$count", 1 ] }, 
        cnt_e3: { $cond: [ { $eq: [ "$Status", "Completed" ] }, "$count", 1 ] }, 
    } }, 
    { $group: { _id: "$startdate", cnt_e1: { $sum: "$cnt_e1" }, cnt_e2: { $sum: "$cnt_e2" }, cnt_e3: { $sum: "$cnt_e3" } } }, 
    { $sort: { _id: 1 } }, 
+2

請你能告訴我們你的文件嗎? – styvane 2015-02-10 21:36:51

+0

會有多個記錄與系統,日期,每事件不斷變化。 – pmclean1964 2015-02-11 00:15:05

+0

請勿在此處添加文檔。編輯你的問題來添加它。 – styvane 2015-02-11 04:44:47

回答

0

下面的代碼...

db.TransactionLogs.aggregate([ { $project: { startdate: {$substr:["$startDate",0,10]}, 
        cnt_e1: { $cond: [ { $eq: [ "$Status", "Error" ] }, "$count", 1 ] }, 
        cnt_e2: { $cond: [ { $eq: [ "$Status", "Warning" ] }, "$count", 1 ] }, 
        cnt_e3: { $cond: [ { $eq: [ "$Status", "Completed" ] }, "$count", 1 ] }, 
    } }, 
    { $group: { _id: "$startdate", cnt_e1: { $sum: "$cnt_e1" }, cnt_e2: { $sum: "$cnt_e2" }, cnt_e3: { $sum: "$cnt_e3" } } }, 
    { $sort: { _id: 1 } },