MongoDb aggregation Group by Date

前端 未结 3 2008
离开以前
离开以前 2021-02-08 00:57

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         


        
3条回答
  •  死守一世寂寞
    2021-02-08 01:51

    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:

    1. $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");
    2. $group groups by day, adding (summing) the number 1 for each matching document;
    3. $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.

提交回复
热议问题