Monday, March 17, 2014

A Few ObjectId Tricks

http://www.mongotips.com/b/a-few-objectid-tricks/

To and From Strings

First off, it is quite simple to switch back and forth between object id and string, which is useful in JSON/XML serialization and in finding Mongo documents from params.
id = BSON::ObjectId.new 
# => BSON::ObjectId('4d6e5acebcd1b3fac9000002') 
id.to_s 
# => "4d6e5acebcd1b3fac9000002" 
BSON::ObjectId.from_string(id.to_s) 
# => BSON::ObjectId('4d6e5acebcd1b3fac9000002') 

Generation Time

Switching back and forth between strings is simple and obvious. Something a little more interesting is that pretty much every driver supports extracting the generation time from an object id. This means that you can stop using created_at in your Mongo documents and instead just pull it from the object id. We are doing this in Gaug.es quite often.
BSON::ObjectId.new.generation_time 
# => 2011-03-02 15:01:08 UTC
The generation time is UTC and you can easily use ActiveSupport’s awesome TimeZone stuff to move the time into different zones.

id = BSON::ObjectId.new 
id.generation_time.in_time_zone(Time.zone)

No comments: