If you want to get all new things in the past 5 minutes you would have to do some calculations, but its not hard...
First create an index on the property you want to match on (include sort direction -1 for descending and 1 for ascending)
db.things.createIndex({ createdAt: -1 }) // descending order on .createdAt
Then query for documents created in the last 5 minutes (60 seconds * 5 minutes)....because javascript's .getTime() returns milliseconds you need to mulitply by 1000 before you use it as input to the new Date() constructor.
db.things.find({
createdAt: {
$gte: new Date(new Date().getTime()-60*5*1000).toISOString()
}
})
.count()
Explanation for new Date(new Date().getTime()-60*5*1000).toISOString() is as follows:
First we calculate "5 minutes ago":
new Date().getTime() gives us current time in milliseconds
- We want to subtract 5 minutes (in ms) from that:
5*60*1000 -- I just multiply by 60 seconds so its easy to change. I can just change 5 to 120 if I want 2 hours (120 minutes).
new Date().getTime()-60*5*1000 gives us 1484383878676 (5 minutes ago in ms)
Now we need to feed that into a new Date() constructor to get the ISO string format required by MongoDB timestamps.
{ $gte: new Date(resultFromAbove).toISOString() } (mongodb .find() query)
- Since we can't have variables we do it all in one shot:
new Date(new Date().getTime()-60*5*1000)
- ...then convert to ISO string:
.toISOString()
new Date(new Date().getTime()-60*5*1000).toISOString() gives us 2017-01-14T08:53:17.586Z
Of course this is a little easier with variables if you're using the node-mongodb-native driver, but this works in the mongo shell which is what I usually use to check things.