Question

I'm getting a timestamp from my MongoDB database, but it's coming back with precision only in the seconds:

Thu Jun 06 2013 16:15:22 GMT-0400 (Eastern Daylight Time)

I need greater granularity. Is there a way to get a MongoDB timestamp with precision in the milliseconds?

I'm making the call on my node.js server via mongoose:

var timestamp = new ObjectID().getTimestamp();

How can I get something more precise?

Was it helpful?

Solution

ObjectIds are stored with the precision of seconds and you can't change it. So if you need something of millis granularity then you have to store your own timestamp value.

OTHER TIPS

I generated timestamps one after another and got these:

ObjectId("586a291570b9a181fc2f61ba").getTimestamp();
ISODate("2017-01-02T10:19:01Z")

For the next timestamp:

ObjectId("586a291570b9a181fc2f61bc").getTimestamp();
ISODate("2017-01-02T10:19:01Z") 

You'll notice that although the only granularity printed by getTimestamp() is in seconds, there is a further granularity which causes the ObjectId string to vary even though both of them are at 01 second.

The reason:

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. Timestamp values are a 64 bit value where:

    the first 32 bits are a time_t value (seconds since the Unix epoch)
    the second 32 bits are an incrementing ordinal for operations within a given second.

Within a single mongod instance, timestamp values are always unique.  

So the true granularity is in terms of the 32 bit ordinal generated by MongoDB. It is related to the operations within a second, and not to a time value, so you don't get it in terms of millisecond.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top