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?
If you're not using any other indexes and are using the default ObjectID as your _id, you can do the following:
db.collection.find({
_id: {
$gt: ObjectID.createFromTimestamp(Date.now()*1000 - 24*60*60)
}
}, callback)
For anyone else landing here via google, you can do this in the mongo shell as follows:
db.collection.find({ $where: function () { return Date.now() - this._id.getTimestamp() < (24 * 60 * 60 * 1000) } })
first of all it would really help if you will provide people with a schema of your collection.
But just because it already 3 hours passed and no one replied I will try:
Suppose you have you entry and it has a field createdAt which is an ISODate:
{
somefield: "test",
createdAt: ISODate("2012-08-13T04:00:00Z")
}
So what you need to do is to put an index on this field
db.yourColl.ensureIndex({createdAt:1});
Then you get your current time in node.js substitute your 24 hours and get your value of start. (As far as I know there is no analog of NOW in mongdb. Right me someone if I am wrong.)
db.yourColl.find({
createdAt: {
$gte: start
}
});