mongodb中的聚合和MapReduce

时间:2018-01-16 10:51:26

标签: mongodb mapreduce aggregation-framework aggregation

我有错误日志的集合,包含错误类型和错误日志的日期,因为我需要执行的error_type和error_date.what是特定月份类型的组错误日志,我使用$ 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吗?任何建议和帮助都非常感谢

1 个答案:

答案 0 :(得分:1)

您可以将$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: {'_id': -1}}