![](/img/trans.png)
[英]Is there a way to convert createdAt from MongoDB in the format of "day ago" when passing multiple posts with multiple days in one object?
[英]Query MongoDb records from 5 days ago using '_id'
我已经在线阅读了'_id'的时间戳,它是何时创建的,您可以根据日期进行查询。 这是我到目前为止尝试过的,但是没有任何运气。
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);
});
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%"
},
...
非常感谢@robertklep与我一起完成此工作。 如果还有其他人遇到此问题,下面是有关解决方法的解决方案。
更新的答案:
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);
...
});
您需要根据时间戳创建一个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
之后,您可以使用_id
进行比较查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.