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

后端 未结 7 1987
遇见更好的自我
遇见更好的自我 2020-12-03 04:41

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

相关标签:
7条回答
  • 2020-12-03 05:06

    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)
    
    0 讨论(0)
  • 2020-12-03 05:07

    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.

    0 讨论(0)
  • 2020-12-03 05:08

    "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();
    
    0 讨论(0)
  • 2020-12-03 05:12

    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
       }
    });
    
    0 讨论(0)
  • 2020-12-03 05:17

    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)
         }
    }
    
    0 讨论(0)
  • 2020-12-03 05:21

    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);
    });
    
    0 讨论(0)
提交回复
热议问题