1

oplog 有一个名为 ts 的字段,如下所示:

{"ts":"6533707677506207745","t":2,"h":"-7325657776689654694", ...}

我想查询oplog,像这样:

db.oplog.rs.find({ts:{$gt:x}});

如何生成代表现在的时间戳?现在之前 30 秒怎么样?

如果我做:

const x = new Timestamp();

我收到一条错误消息:

在此处输入图像描述

生成时间戳的正确方法是什么?如何使用正确的 ts 值查询 oplog?

以下是时间戳的文档:http: //mongodb.github.io/node-mongodb-native/core/api/Timestamp.html

但我无法弄清楚低数字/高数字是什么意思。

4

2 回答 2

1

该时间戳是 UNIX 纪元的秒数​​,而 Date() 是毫秒。所以...

db.oplog.rs.find({ts:{$gt:Timestamp((new Date().getTime()-30000)/1000,0)}})

我们在这里所做的是获取 30000 毫秒前的当前时间,将其除以 1000 以获取秒数,然后将(需要的)第二个参数添加到 Timestamp -function。

编辑:当然,如果您需要确切的 Timestamp() 值,则将 (new Date().getTime()-30000)/1000 的小数部分填充为第二个参数。

var x=(new Date().getTime()-30000)/1000;
var y=Math.floor(x);
var z=Math.round((x-y)*1000);
db.oplog.rs.find({ts:{$gt:Timestamp(y,z)}})
于 2018-03-17T11:46:22.027 回答
0

这似乎产生了当前时间,但坦率地说,我不知道为什么:

import {Timestamp} from 'bson';
const t = new Timestamp(1, Math.ceil(Date.now()/1000));

该值可用于查询数据库中具有时间戳字段的字段,如下所示:

query.ts = {$gt: t};
const q = coll.find(query);
于 2018-03-17T01:19:38.487 回答