Search code examples
mongodbdatetimemongodb-queryaggregation-frameworkmongodb-aggregation

The most efficient way to returning today's documents from a collection


I have a collection where all the documents in that collection have a datetime timestamp that includes the time as well as the date.

When using the aggregation framework how do I say give me the values for today? The following only gives me the entries for midnight.

db.strategy.aggregate(
    [
        {
            $match: {
             "date": new Date()
            }
        },

    ]
);

Solution

  • To get the documents which have datetime values for today, you need to create a date query range where the start date object should hold the current date time hours at 00:00:00.000 (milliseconds precision) and set the hours for today's date to 23:59:59.999 to the end date variable.

    For example:

    // Create the start date which holds the beginning of today
    var todayStart = new Date();
    todayStart.setHours(0,0,0,0);
    
    // Create the end date which holds the end of today
    var todayEnd = new Date();
    todayEnd.setHours(23,59,59,999);
    
    // Create the date range query object
    var query = {
        "date": {
            $gte: todayStart,
            $lte: todayEnd
        }
    };
    
    // using the find() method
    db.strategy.find(query); 
    

    Or using the aggregate() method as

    db.strategy.aggregate({ "$match": query });