2015-02-10 153 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 } },