In Mongo shell, how would I filter records that have been added today (or on a specific date)? I have no specific field of the timestamp of new records, but I guess it can be restored from ObjectID.
Asked
Active
Viewed 1.7k times
7
-
1@cubbuk I think that `$where` was not yet implemented for mongo shell that days. – thanasisp Feb 25 '17 at 15:40
-
1@thanasisp $where requires table scan as it needs to evaluate where expression on each record, thus has low performance – cubbuk Feb 25 '17 at 15:44
-
@cubbuk of course it does. – thanasisp Feb 25 '17 at 15:49
2 Answers
10
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.

thanasisp
- 5,855
- 3
- 14
- 31
4
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)
}
}
);

wscourge
- 10,657
- 14
- 59
- 80