首页 文章

MongoDB中的聚合查询

提问于
浏览
-1

我正在尝试从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" }

我确信它对我的聚合缺乏了解 . 任何帮助或方向非常感谢!

我想到了 . 我需要看看如何在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 } },

1 回答

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

相关问题