4

I'm querying to Oplog using mongoose in node.js, to get the timestamp of the last oplog record using the following code:

oplogModel.find().sort('-ts').limit(1).select('ts').exec(function(err, res){
    if (err) {console.log(err);}
    lastTimestamp=res[0];
    console.log(JSON.stringify(lastTimestamp));
});

But the output I'm getting is {"ts":"6260013777081597954"}

When I run this in mongo shell,

rs0:PRIMARY> db.oplog.rs.find({}, {ts:1, _id:0}).sort({ts:-1}).limit(1);

I get : { "ts" : Timestamp(1457523037, 2) }

How can I convert {"ts":"6260013777081597954"} to epoch time or iso time? What format is this timestamp in?

Shipra
  • 1,259
  • 2
  • 14
  • 26
  • The [documentation](https://docs.mongodb.org/manual/reference/bson-types/#timestamps) should help here. – chridam Mar 10 '16 at 12:20
  • There is something going wrong here. Converting the timestamp you get in Mongo to an integer using the [`bson-timestamp`](https://www.npmjs.com/package/bson-timestamp) library gives a completely different result – elssar Mar 10 '16 at 12:53

1 Answers1

1

The output you are getting is because of the line console.log(JSON.stringify(lastTimestamp)) since JSON.stringify(lastTimestamp) parses the resulting object to string.

In essence you need to convert the timestamp to a 32-bit int:

oplogModel.find().sort('-ts').limit(1).select('ts').exec(function(err, res){
    if (err) {console.log(err);}
    lastTimestamp=res[0].ts;
    console.log(lastTimestamp); // 6260013777081597954

    var h = 4294967296, // 2^32
        timestamp = Math.floor(lastTimestamp / 4294967296), // convert to 32-bit int
        date = new Date(timestamp * 1000); // Date() expects milliseconds.

    console.log(date);
});

When you get { "ts" : Timestamp(1457523037, 2) } in mongo shell, the first parameter represents a 32-bit value indicating seconds since the unix epoch and the second parameter is 32-bit ordinal value is for ordering operations occuring in the same second.

For more details, refer to the documentation but keep in mind that the BSON timestamp type is for internal MongoDB use and in your own data you should prefer the Date type.

chridam
  • 100,957
  • 23
  • 236
  • 235
  • I'm querying oplog which is an internal read-only collection, hence I cannot choose it's datetime. – Shipra Mar 10 '16 at 14:53