Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Only fetch documents created in the last 24hrs?

Tags:

mongodb

I want to limit a query I'm making to only look in documents that were created in the past 24 hrs.

What is the best way to structure this query? How do I go about limiting based on date?

like image 354
boom Avatar asked Nov 09 '12 19:11

boom


2 Answers

Add createdAt field, index it, then query

db.getCollection("COLLECTION_NAME").find({"createdAt":{$gt:new Date(Date.now() - 24*60*60 * 1000)}}) 

This will return all records older then 86400 seconds.

like image 107
spicydog Avatar answered Sep 23 '22 10:09

spicydog


If you're not using any other indexes and are using the default ObjectID as your _id, you can do the following:

var ObjectID = require('mongodb').ObjectID  db.collection.find({   _id: {     $gt: ObjectID.createFromTime(Date.now() / 1000 - 24*60*60)   } }, callback) 
like image 40
Jonathan Ong Avatar answered Sep 26 '22 10:09

Jonathan Ong