I'm new to Mongoid. In my model file, I've created a field with data type BigDecimal. I want to store time stamp in it. Below is the model that I'm using:
class Test
include Mongoid::Document
field :time_stamp, type: BigDecimal
end
And Below is the code that I'm using to create a document:
aTime = "Wed Apr 24 09:48:38 +0000 2013"
timest = aTime.to_time.to_i
Test.create({time_stamp: timest})
I see that the time_stamp is stored as String in the database. Can anybody direct me to store the timestamp as number in DB so that I could perform some operations on it. Thanks in advance.
Working of the timestamp in mongodb is simple, where when executed, the timestamp method will call the currentDate(), which will pick the current date and time of the system. This picked date and time will be stored in the collection, along with the other data values.
Timestamps. BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. This internal timestamp type is a 64 bit value where: the most significant 32 bits are a time_t value (seconds since the Unix epoch)
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
According to this answer, the numeric types supported by MongoDB are:
MongoDB stores data in a binary format called BSON which supports these numeric data types:
int32 - 4 bytes (32-bit signed integer)
int64 - 8 bytes (64-bit signed integer)
double - 8 bytes (64-bit IEEE 754 floating point)
Reinforced by this statement in the Mongoid documentation:
Types that are not supported as dynamic attributes since they cannot be cast are:
BigDecimal
Date
DateTime
Range
I don't know about the things you want to with the field, but if you really want it stored as a number, you have to use a different numeric type that is supported by the MongoDB (BSON), probably Float
or Integer
.
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