1

The oplog has a field called ts, which looks like this:

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

I want to query the oplog, like so:

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

how can I generate a Timestamp, that represents now? How about 30 seconds before now?

if I do:

const x = new Timestamp();

I get a error saying:

enter image description here

What is the correct way to generate a Timestamp? How can I query the oplog with the right ts value?

Here are the docs for Timestamp: http://mongodb.github.io/node-mongodb-native/core/api/Timestamp.html

but I cannot figure out what low number/high number is about.

2 Answers2

1

That timestamp is seconds from the UNIX epoch and Date() is milliseconds. So...

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

What we do here is get current time 30000 milliseconds ago, divide that with 1000 to get seconds and then add (needed) second parameter to Timestamp -function.

Edit: Of course, if you need exact Timestamp() value, you fill that decimal part of (new Date().getTime()-30000)/1000 as second parameter.

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)}})
JJussi
  • 1,540
  • 12
  • 12
  • 1
    thanks, what is the first and second arg to Timestamp? (low and high bits right?)...can you explain that a little more? I don't get it. –  Mar 17 '18 at 19:59
  • this question is similar: https://stackoverflow.com/questions/49333616/get-correct-timestamp-for-45-seconds-ago –  Mar 17 '18 at 20:02
  • Yes, it's Timestamp(,), so actually, after divide of 1000 you could take that decimal part and put it there as second parameter. I used zero, so every event after that is listed. – JJussi Mar 18 '18 at 05:55
0

this seems to yield the current time, but I frankly do not know why:

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

this value can be used to query a field in the db, that has a timestamp field, like so:

query.ts = {$gt: t};
const q = coll.find(query);