I\'m trying to group by timestamp for the collection named \"foo\" { _id, TimeStamp }
db.foos.aggregate(
[
{$group : { _id : new Date (Date.UTC({ $year : \'$T
db.foos.aggregate(
[
{ $project : { day : {$substr: ["$TimeStamp", 0, 10] }}},
{ $group : { _id : "$day", number : { $sum : 1 }}},
{ $sort : { _id : 1 }}
]
)
Group by date can be done in two steps in the aggregation framework, an additional third step is needed for sorting the result, if sorting is desired:
$project
in combination with $substr
takes the first 10 characters (YYYY:MM:DD) of the ISODate object from each document (the result is a collection of documents with the fields "_id" and "day");$group
groups by day, adding (summing) the number 1 for each matching document;$sort
ascending by "_id", which is the day from the previous aggregation step - this is optional if sorted result is desired.This solution can not take advantage of indexes like db.twitter.ensureIndex( { TimeStamp: 1 } )
, because it transforms the ISODate object to a string object on the fly. For large collections (millions of documents) this could be a performance bottleneck and more sophisticated approaches should be used.