MongoDB:仅获取过去 24 小时内创建的文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13314678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:55:40  来源:igfitidea点击:

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

mongodb

提问by boom

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

我想限制我正在执行的查询仅查看过去 24 小时内创建的文档。

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

构建此查询的最佳方法是什么?我如何根据日期进行限制?

回答by spicydog

Add createdAtfield, index it, then query

添加createdAt字段,索引它,然后查询

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

This will return all records older then 86400 seconds.

这将返回所有早于 86400 秒的记录。

回答by Jonathan Ong

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

如果您没有使用任何其他索引并且使用默认 ObjectID 作为您的 _id,您可以执行以下操作:

var ObjectID = require('mongodb').ObjectID

db.collection.find({
  _id: {
    $gt: ObjectID.createFromTime(Date.now() / 1000 - 24*60*60)
  }
}, callback)

回答by Thom Seddon

For anyone else landing here via google, you can do this in the mongo shell as follows:

对于通过 google 登陆这里的其他人,您可以在 mongo shell 中执行以下操作:

db.collection.find({ $where: function () { return Date.now() - this._id.getTimestamp() < (24 * 60 * 60 * 1000)  }  })

回答by jitendra rajput

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);
});

回答by Salvador Dali

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:

但仅仅因为它已经过去了 3 个小时而没有人回复我会尝试:

Suppose you have you entry and it has a field createdAt which is an ISODate:

假设你有你的条目,它有一个字段 createdAt,它是一个 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.)

然后你在 node.js 中得到你当前的时间来代替你的 24 小时并得到你的 start 值。(据我所知,mongdb 中没有 NOW 的类似物。如果我错了,请纠正我。)

db.yourColl.find({
   createdAt: {
     $gte: start
   }
});

回答by Ronak Poriya

"TIME" is field which store timestamp

“TIME”是存储时间戳的字段

db.your_collection_name.find({"TIME":{'$lt': new Date(),'$gte':new Date(new Date().setDate(new Date().getDate()-1))}},{}).count();

回答by Jam M. Hernandez Q.

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.

希望这可以帮助某人。我正在使用 pymongo 查询过去 24 小时的数据。就我而言,我必须将当前时间转换为 BSON 时间戳。

First I had to import Bson timestamp:

首先,我必须导入 Bson 时间戳:

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)
     }
}