Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Mongoid _id into a timestamp (Rails)

I just read this SO post:

How are MongoDB's ObjectIds generated?

According to an answer there MongoDB ID's are not random and can be easily predicted. You can even convert it into a timestamp:

http://www.mongodb.org/display/DOCS/Object+IDs

I was wondering, is it possible to convert an _id (e.g. 52a435840000640002695268 or 52908452636872eda1000000) into a timestamp using the mongoidgem?

like image 493
Cjoerg Avatar asked Dec 11 '25 09:12

Cjoerg


1 Answers

MongoDB IDs are parsed via Mongoid into instances of the class BSON::ObjectId, and that class has a method generation_time - http://rubydoc.info/gems/bson/2.0.0/BSON/ObjectId:generation_time

This gives you the time that the ID was generated at as a Ruby Time object, which I believe is what you were after.

like image 126
sevenseacat Avatar answered Dec 14 '25 07:12

sevenseacat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!