子集上求和的MongoDB阶

子集上求和的MongoDB阶,mongodb,sorting,sum,Mongodb,Sorting,Sum,我有以下收藏: error_reports [ { "_id":{ "$oid":"5184de1261" }, "date":"29/04/2013", "errors":[ { "_id":"10", "failures":2, "alerts":1, }, {

我有以下收藏:

error_reports
[    
    {
       "_id":{
          "$oid":"5184de1261"
       },
       "date":"29/04/2013",
       "errors":[
          {
             "_id":"10",
             "failures":2,
             "alerts":1,
          },
          {
             "_id":"11",
             "failures":7,
             "alerts":4,
          }
       ]
    },
    {
       "_id":{
          "$oid":"5184de1262"
       },
       "date":"30/04/2013",
       "errors":[
          {
             "_id":"15",
             "failures":3,
             "alerts":2,
          },
          {
             "_id":"16",
             "failures":9,
             "alerts":1,
          }
       ]
    }
]
是否可以按故障降序检索包含故障和警报的文档列表?我是mongodb的新手,我已经搜索了2天,但我不知道什么是正确的查询

我试过这样的方法:

db.error_reports.aggregate(
    { $sort : { failures: -1} },
    { $group:
        { _id: "$_id",
        failures: { "$sum": "$errors.failures" }
        }
    }
);

但是它不起作用,我想这是因为
$sum
$errors.failures
的原因,我想在
day\u hours
子集合的每个项目上求和这个属性,但我不知道在查询中如何做…

您的尝试非常接近。唯一缺少的就是这个
$unwind
基本上是基于子文档将每个文档拆分出来。因此,在对故障和警报进行分组之前,请先释放错误,如下所示:

db.error_reports.aggregate(
  { $unwind : '$errors' },
  { $group : {
    _id : '$_id',
    'failures' : { $sum : '$errors.failures' },
    'alerts' : { $sum : '$errors.alerts' }
  } },
  { $sort : { 'failures': -1 } }
);
这将为您提供以下结果:

{
    "result" : [
        {
            "_id" : ObjectId("5184de1262"),
            "failures" : 12,
            "alerts" : 3
        },
        {
            "_id" : ObjectId("5184de1261"),
            "failures" : 9,
            "alerts" : 5
        }
    ],
    "ok" : 1
}

非常感谢,这正是我需要的。我不知道有这样的接线员。