Can I get greater granularity out of a MongoDB timestamp? Can I get greater granularity out of a MongoDB timestamp? mongodb mongodb

Can I get greater granularity out of a MongoDB timestamp?


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.


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.