The documentation mentions the four types of time related field types (http://mongoid.org/en/mongoid/docs/documents.html#fields). In other databases, I can see how these fields are going to be difference types in the database but for MongoDB aren't they all going to be Date types? Is this just for consistency with ActiveRecord?
The recommended way to store dates in MongoDB is to use the BSON Date data type. The. BSON Specification. refers to the Date type as the UTC datetime and is a 64-bit integer. It represents the number of milliseconds since the.
The DATE type in MongoDB can store date and time values as a combined unit. The BSON Date type is a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970).
A field required in every MongoDB document. The _id field must have a unique value. You can think of the _id field as the document's primary key. If you create a new document without an _id field, MongoDB automatically creates the field and assigns a unique BSON ObjectId. accumulator.
Mongoid is the officially supported object-document mapper (ODM) for MongoDB in Ruby. Installation & Configuration. Installation. Compatibility. Configuration.
There are almost no difference between them, all of them wrap Time type. You can change DateTime, Date or TimeWithZone to get instances of this types after unserializing from mongo.
Mongoid extends this classes to add demongoize/mongoize methods for data binding. So the only difference is in implementation.
So Time implementation
def demongoize(object)
return nil if object.blank?
object = object.getlocal unless Mongoid::Config.use_utc?
if Mongoid::Config.use_activesupport_time_zone?
object = object.in_time_zone(Mongoid.time_zone)
end
object
end
def mongoize(object)
return nil if object.blank?
begin
time = object.__mongoize_time__
if object.respond_to?(:sec_fraction)
::Time.at(time.to_i, object.sec_fraction * 10**6).utc
elsif time.respond_to?(:subsec)
::Time.at(time.to_i, time.subsec * 10**6).utc
else
::Time.at(time.to_i, time.usec).utc
end
rescue ArgumentError
EPOCH
end
end
Date implementation
def demongoize(object)
::Date.new(object.year, object.month, object.day) if object
end
def mongoize(object)
unless object.blank?
begin
time = object.__mongoize_time__
::Time.utc(time.year, time.month, time.day)
rescue ArgumentError
EPOCH
end
end
end
You can check other implemetations
https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/date.rb#L46 https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/date_time.rb#L49 https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/time.rb#L48 https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/time_with_zone.rb#L32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With