Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate function in mongodb

I have a 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 an aggreagate output as follows

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

I have tried this code but didn't produce 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}}
])
like image 382
Vignesh Avatar asked Jan 29 '23 02:01

Vignesh


1 Answers

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,
        }
    },

]
);
like image 197
Shubham Avatar answered Feb 05 '23 16:02

Shubham