4

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}} ]) 
3
  • Can you add you scnerio as well as what you want to achieve? To be more descriptive add what you want to achieve . YOUR DATASET doesn't mach to your desire output i think it would be { date:"2017-12-01T00:00:0Z", total:"2", completed:2, failed:0 } Commented Dec 1, 2017 at 8:10
  • @himanshu I have changed the dB data Commented Dec 1, 2017 at 8:45
  • @Himanshusharma i have updated the code please check it Commented Dec 2, 2017 at 7:27

1 Answer 1

8
+50
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, } }, ] ); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.