[英]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.