mongodb中的聚合和MapReduce

mongodb中的聚合和MapReduce,mongodb,mapreduce,aggregation-framework,aggregation,Mongodb,Mapreduce,Aggregation Framework,Aggregation,我有错误日志的集合,错误日志的类型和日期为error\u type和error\u date。我需要执行的是从特定月份的type中分组错误日志,我使用$group作为聚合管道,在月份或从错误类型中分组。我们希望得到的数据是这样的 [{ _id: 10, ///month wise group logs: { error_type1: ["error logs array of type 1"], error_type2: ["error logs array of typ

我有错误日志的集合,错误日志的类型和日期为error\u type和error\u date。我需要执行的是从特定月份的type中分组错误日志,我使用$group作为聚合管道,在月份或从错误类型中分组。我们希望得到的数据是这样的

[{
  _id: 10, ///month wise group
  logs: {
    error_type1: ["error logs array of type 1"],
    error_type2: ["error logs array of type 2"]
  }
},
{
  _id: 11, ///month wise group
  logs: {
    error_type1: ["error logs array of type 1"],
    error_type2: ["error logs array of type 2"]
  }
}]
我的聚合代码目前是

 rfidAttErrorSchema.aggregate([{
      $match: condition
    }, {
      $group: {
        _id: {
          $month: "$error_date"
        },
        logs: {
          $push: "$$ROOT"
        }
      }
    }, {
      $sort: {
        'error_date': -1
      }
    }
  ],
  function (err, data) {
    if (err) {
      return res.status(500).json({
        result: err
      });
    }
    console.log("data is  now  data", data);
    res.json({
      result: data
    });
});

有人能帮我使用$group聚合管道两次或使用MongoDB的MapReduce获得这个吗?非常感谢您的任何建议和帮助

您可以将
$group
替换为

{ $group: { _id: { month:{$month: "$error_date"}, error_type:"$error_type", }, data: { $push: "$$ROOT" } } }, 
{ $group: { _id: "$_id.month", logs: { $push: {error_type:"$_id.error_type",data:"$data" } } } }
对于预期格式,您可以使用3.4.4
$arrayToObject
将键转换为命名键

{ $group: { _id: { month:{$month: "$error_date"}, error_type:"$error_type", }, data: { $push: "$$ROOT" } } }, 
{ $group: { _id: "$_id.month", logs: { $push: {k:"$_id.error_type",v:"$data" } } } }, 
{ $addFields:{logs:{"$arrayToObject":"$logs"}}}

调整
$sort
以包括月份
{$sort:{u id:-1}

您保存的我:)