简体   繁体   English

使用'_id'查询5天前的MongoDb记录

[英]Query MongoDb records from 5 days ago using '_id'

I've read online that '_id' holds a timestamp on when it was created and you are able to query it depending on a date. 我已经在线阅读了'_id'的时间戳,它是何时创建的,您可以根据日期进行查询。 This is what I've I tried so far, but not having any luck. 这是我到目前为止尝试过的,但是没有任何运气。

var d = new Date();
d.setDate(d.getDate() - 5);

collection.find( { }, { metal: 1, change: 1, percent: 1, _id: { $gte: d } } ).toArray(function(err, results) {
    console.log(results);
});

Array in Mongo: Mongo中的数组:

[
    {
        "_id": "58e21b52524c0b0011fb92f4",
        "metal": "Palladium",
        "change": 3,
        "percent": "+0.38%"
    },
    {
        "_id": "58e21ee3524c0b0011fb92f5",
        "metal": "Gold",
        "change": 6,
        "percent": "+0.54%"
    },
    {
        "_id": "58e21ee3524c0b0011fb92f6",
        "metal": "Silver",
        "change": 0,
        "percent": "+0.77%"
    },
...

Much thanks to @robertklep for working through this with me. 非常感谢@robertklep与我一起完成此工作。 If anyone else runs into this problem, below is a solution on how to solve it. 如果还有其他人遇到此问题,下面是有关解决方法的解决方案。

Updated Answer: 更新的答案:

const ObjectID = require('mongodb').ObjectID;
var d = new Date();
d.setDate(d.getDate() - 1); //1 would be 1day
var _id = ObjectID.createFromTime(d.getTime() / 1000);

collection.find({ _id : { $gte : _id }}, { metal: 1, change: 1, percent: 1 }).toArray(function(err, results) {
  console.log(results);
   ...
});

You need to create an ObjectID from your timestamp, for which you can use ObjectID.createFromTime() : 您需要根据时间戳创建一个ObjectID ,可以使用ObjectID.createFromTime()

const ObjectID = require('mongodb').ObjectID;

var d = new Date();
d.setDate(d.getDate() - 5);

var _id = ObjectID.createFromTime(d.getTime() / 1000); // timestamp should be in seconds

After that, you can use _id for comparison queries. 之后,您可以使用_id进行比较查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM