Aggregate function in mongodb

I have db data as follows

{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "COMPLETED"},{
"_id" : ObjectId("5a2109572222085be93ef10d"),
"name" : "data1",
"date" : "2017-12-01T00:00.0Z",
"status" : "FAILED"}

and I want to get aggreagate result as follows

{date: "2017-12-01T00: 00: 0Z", total: "2", completed: 1, failed: 1}

I tried this code but did not give the result as above

db.test.aggregate([
{$group: {_id : {date : '$date',status:'$status'}, total:{$sum :1}}},
{$project : {date : '$_id.date', status : '$_id.status', total : '$total', _id : 0}}
])
+4
source share
1 answer
db.test.aggregate(

// Pipeline
[
    // Stage 1
    {
        $group: {
         _id:"$date",
         total:{$sum:1},
         failed:{$sum:{$cond:[{$eq:["$status","FAILED"]},1,0]}},
         completed:{$sum:{$cond:[{$eq:["$status","COMPLETED"]},1,0]}}
        }
    },

    // Stage 2
    {
        $project: {
            date : '$_id',
            total : 1,
            failed : 1,
            completed : 1,
            _id : 0,
        }
    },

]
);
+8
source

Source: https://habr.com/ru/post/1690117/


All Articles