I have a collection called Document in MongoDB. Documents in this collection have a field called CreationDate stored in ISO date type. My task is to count the number of docu
In case some poor souls stumble across this question in 2017, like me: As of Mongo 3.0 there is now a dateToString operator available
which means if you have proper Date()'s you should be able to do simply:
db.Document.aggregate(
, {$project: {_id:1, CreationDate:1}
, {$group: {
_id : { $dateToString: { format: "%Y-%m-$d", date: "$CreationDate" } },
cnt:{$sum:1}}}
, {$sort:{'cnt':-1}}
);
For those of us who happen to have dates stored in non-date field (what joy!) you can create a new Date() object in the project step. In my case, the date was stored as a number of milliseconds (integer) and I add the number of milliseconds to the 0-Date.
db.Document.aggregate(
, {$project: {
_id:1,
CreationDate: {"$add": [ new Date(0), "$CreatedOn" ]}
}
, {$group: {
_id : { $dateToString: { format: "%Y-%m-$d", date: "$CreationDate" } },
cnt:{$sum:1}}}
, {$sort:{'cnt':-1}}
);