MongoDB find today's records

we can use $where

db.collection.find(
   { $where: "this._id.getTimestamp() >= ISODate('2017-02-25')" }
)

To get documents for today, or better say from last midnight:

db.collection.find( { $where: function() { 
    today = new Date(); //
    today.setHours(0,0,0,0);
    return (this._id.getTimestamp() >= today)
} } );

of course it is much faster to have an indexed timestamp field or to follow the approach with the calculation of an ObjectID for the start date and compare _id against it, as _id is indexed too.


To get all the records from today:

var startOfToday = new Date();
startOfToday.setHours(0,0,0,0);
// creates ObjectId() from date:
var _id = Math.floor(startOfToday.getTime() / 1000).toString(16) + "0000000000000000";

> db.collection("records")
    .find( { _id: { $gte: ObjectId(_id) } });

To get all the records from the given time period (example: yesterday):

var yesterdayStart = new Date();
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
yesterdayStart.setHours(0,0,0,0);
var startId = Math.floor(yesterdayStart.getTime() / 1000).toString(16) + "0000000000000000";

var yesterdayEnd = new Date();
yesterdayEnd.setDate(yesterdayEnd.getDate() - 1);
yesterdayEnd.setHours(23,59,59,999);
var endId = Math.floor(yesterdayEnd.getTime() / 1000).toString(16) + "0000000000000000";

> db.collection("records")
    .find( { _id: { 
                    $gte: ObjectId(startId),
                    $lte: ObjectId(endId)
                  } 
           }
    );

Tags:

Mongodb