I have a collection of 1000 documents like this:
{ "_id" : ObjectId("628b63d66a5951db6bb79905"), "index" : 0, "name" : "Aurelia Gonzales", "isActive" : false, "registered" : ISODate("2015-02-11T04:22:39.000+0000"), "age" : 41, "gender" : "female", "eyeColor" : "green", "favoriteFruit" : "banana", "company" : { "title" : "YURTURE", "email" : "[email protected]", "phone" : "+1 (940) 501-3963", "location" : { "country" : "USA", "address" : "694 Hewes Street" } }, "tags" : [ "enim", "id", "velit", "ad", "consequat" ] } I want to group those by year and gender. Like In 2014 male registration 105 and female registration 131. And finally return documents like this:
{ _id:2014, male:105, female:131, total:236 }, { _id:2015, male:136, female:128, total:264 } I have tried till group by registered and gender like this:
db.persons.aggregate([ { $group: { _id: { year: { $year: "$registered" }, gender: "$gender" }, total: { $sum: NumberInt(1) } } }, { $sort: { "_id.year": 1,"_id.gender":1 } } ]) which is return document like this:
{ "_id" : { "year" : 2014, "gender" : "female" }, "total" : 131 } { "_id" : { "year" : 2014, "gender" : "male" }, "total" : 105 } Please guide to figure out from this whole.
$first, total$first