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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With