Reputation: 484
I have collections of error logs with the type of error and date of the error log, as error_type and error_date.what I need to perform is group error logs from type in the particular month, I used the $group as aggregation pipeline to group either in month or from error type. what is wish to get data are like this
[{
_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"]
}
}]
and my aggregation code currently is
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
});
});
can someone help me to get this using $group aggregation pipeline twice or using MapReduce of MongoDB? any suggestions and help are highly appreciated
Upvotes: 0
Views: 61
Reputation: 75934
You can replace $group
with
{ $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" } } } }
For expected format you can use 3.4.4 $arrayToObject
to convert the keys into named keys.Something like
{ $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"}}}
Adjust the $sort
to include the month {$sort: {'_id': -1}}
Upvotes: 1