44

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?

spicydog
  • 1,644
  • 1
  • 17
  • 32
boom
  • 10,856
  • 9
  • 43
  • 64
  • This link might help http://stackoverflow.com/questions/8665731/find-last-document-of-the-day-for-the-last-7-days – Mihai Nov 09 '12 at 19:33
  • Start with [docs on native driver](http://mongodb.github.com/node-mongodb-native/). I personally use [mongoskin](https://github.com/kissjs/node-mongoskin). There's also [mongoose](http://mongoosejs.com/) and [others](https://npmjs.org/browse/keyword/mongodb). And of course see [DB's docs](http://www.mongodb.org/display/DOCS/Home) itself (on [queries](http://www.mongodb.org/display/DOCS/Querying) and other stuff). There's also free [M101: MongoDB for Developers](https://education.10gen.com/courses/10gen/M101/2012_Fall/about) from 10gen. – Aleksei Zabrodskii Nov 09 '12 at 19:55
  • @elmigranto i use node-mongodb-native // i know how to use mongo i just don't know the best way to do this query. – boom Nov 09 '12 at 19:57
  • 2
    Create `createdAt` field, create index on that, use `find({gte: isoDate})`. That's what I would do. – Aleksei Zabrodskii Nov 09 '12 at 20:02

12 Answers12

55

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 younger than 86400 seconds.

nullromo
  • 2,165
  • 2
  • 18
  • 39
spicydog
  • 1,644
  • 1
  • 17
  • 32
21

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)
Arpit Suthar
  • 754
  • 1
  • 5
  • 19
Jonathan Ong
  • 19,927
  • 17
  • 79
  • 118
13

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)  }  })
Thom Seddon
  • 1,485
  • 2
  • 15
  • 25
6

Use this in mongoose

let ObjectId    = require('mongodb').ObjectID;

Property.find({
    _id: {
        $gt: ObjectId.createFromTime(Date.now() / 1000 - 24 * 60 * 60)
    }
}, (err, result) => {
    console.log(err || result);
});
jitendra rajput
  • 612
  • 10
  • 15
3

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
   }
});
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
3

Hope this helps someone. I'm using pymongo to query last 24 hours of data. In my case I had to convert the current time into BSON timestamp.

First I had to import Bson timestamp:

from bson.timestamp import Timestamp

Then in my search query I did the following:

yesterday  = datetime.datetime.now() - datetime.timedelta(days=1)

findQuery = {
    "unix": {
        "$gte": Timestamp(int(yesterday.strftime("%s")),0)
     }
}
1

Starting in Mongo 5.0, it's a nice use case for the new $dateDiff aggregation operator:

// { "_id" : ObjectId("60c8f804fb832fe2f2011657") }
db.collection.aggregate([
  { $match: { $expr:
    { $lt: [{ $dateDiff: { startDate: "$_id", endDate: "$$NOW", unit: "hour" } }, 24 ]}
  }}
])
// { "_id" : ObjectId("60c8f804fb832fe2f2011657") } // if document created within the last 24 hours

A few things to note:

  • Basically, we're $matching items for which the duration ($dateDiff) between their creation date (represented by their _id) and now ($$NOW) is less ($lt) than 24 hours.

  • The start date is the $_id (ObjectId):

    • Indeed, an ObjectId contains the timestamp of its creation
    • And $dateDiff can accept an ObjectId as a temporal representation
  • The end date is $$NOW, which is a variable that returns the current datetime value.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
0

"TIME" is field which store timestamp

db.your_collection_name.find({"TIME":{'$lt': new Date(),'$gte':new Date(new Date().setDate(new Date().getDate()-1))}},{}).count();
Ronak Poriya
  • 2,369
  • 3
  • 18
  • 20
0

Some solutions are outdate new Date() etc. This will work in 2022 with updated golang:

Remember to include time module

import (
    "time")

Will use basic minute with - operator. Below it means 24 hours multiply with 60 minutes and .Add actually subtracts with minus operator:

"$gt": time.Now().Add(-60 * 24 * time.Minute),

İnclude filters:

filter := bson.M{
            "$and": []bson.M{
        {
            "createdat": bson.M{
                "$gt": time.Now().Add(-60 * 24 * time.Minute),
            },
        },
        {
            "userid": userid,
        },
        }}

Make sure defer cureser

cursor, _ := todoCollection.Find(ctx, filter, findOptions)

    for cursor.Next(ctx) {
        var product models.ProductPost
        cursor.Decode(&product)
        products = append(products, product)
    }
    defer cursor.Close(ctx)

Get the length

fmt.Println(len(products))
Bitfinicon
  • 1,045
  • 1
  • 8
  • 22
0
await db.yourColl.find({
   "timestamp": {
       $lt: new Date(),
       $gte: new Date(new Date().setDate(new Date().getDate()-(24* 60 * 60 * 1000)))
   }
})

Works in my case

incalite
  • 3,077
  • 3
  • 26
  • 32
-1

I had the same problem and after a lot of searches, the best solution that I found for fetching data from last X days is something like this:

let date_obj = new Date();
let requestedTime = new Date(new Date().setDate(date_obj.getDate() - day));
    
    db.collection.find({
      createdAt: {$gt: requestedTime}
    });

the day variable must be a numeric value of the number of days you want, for example: 1 for one day ago (last 24 hours), 2 for two days ago (last 48 hours), 30 for the last month, 60 for the last two months, and so on. ..

let date_obj = new Date();
let requestedTime = new Date(new Date().setDate(date_obj.getDate() - 1));

document.querySelector("#current_date").innerHTML = `current date: ${date_obj}`
document.querySelector("#last_24H_date").innerHTML = `last 24 hours: ${requestedTime}`
<div id="current_date"></div>
<div id="last_24H_date"></div>
-1
db.video.find({"timestamp":{$lt: new Date(),$gte: new Date(new Date().setDate(new Date().getDate()-1))}})
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 4
    Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem. – 4b0 Jul 20 '21 at 12:07
  • 3
    To expand on @shree's point, that's _especially_ true here, where there are **nine** other answers, some with quite a few upvotes, and most with explanations. If a new reader comes to this page and is trying to find a solution, what sets your approach apart from the existing answers? Under what conditions might your answer by preferred? Are you using new syntax that wasn't available when the question was first asked? That's the type of information that will make your answer a useful contribution to this thread. – Jeremy Caney Jul 20 '21 at 19:02