MongoDB中的聚合查询

时间:2015-02-10 21:31:04

标签: mongodb aggregation-framework

我试图从MongoDB表创建一些每日统计数据。该文档包含具有创建日期,状态(警告,错误,完成)的消息。我想生成一个查询,每个日期产生一条记录,警告计数,错误计数,完成计数。我是Mongo的新手,只是学习查询语言。我尝试使用混合结果进行聚合:

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" }

我确信我对聚合缺乏了解。非常感谢任何帮助或指导!

我明白了。我需要看看如何" pivot"在蒙戈。这有效:

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 } },

1 个答案:

答案 0 :(得分: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 } },