Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting timestamp from mongodb id

How do I get the timestamp from the MongoDB id?

like image 252
Harry Avatar asked Jun 23 '11 09:06

Harry


2 Answers

The timestamp is contained in the first 4 bytes of a mongoDB id (see: http://www.mongodb.org/display/DOCS/Object+IDs).

So your timestamp is:

timestamp = _id.toString().substring(0,8) 

and

date = new Date( parseInt( timestamp, 16 ) * 1000 ) 
like image 157
Kolja Avatar answered Sep 16 '22 23:09

Kolja


As of Mongo 2.2, this has changed (see: http://docs.mongodb.org/manual/core/object-id/)

You can do this all in one step inside of the mongo shell:

document._id.getTimestamp(); 

This will return a Date object.

like image 34
Chris Lynch Avatar answered Sep 20 '22 23:09

Chris Lynch