将时间戳存储为数字Mongoid

sen*_*hil 13 ruby-on-rails mongoid

我是Mongoid的新手.在我的模型文件中,我创建了一个数据类型为BigDecimal的字段.我想在其中存储时间戳.以下是我正在使用的模型:

class Test
  include Mongoid::Document
  field :time_stamp, type: BigDecimal
end
Run Code Online (Sandbox Code Playgroud)

以下是我用来创建文档的代码:

aTime = "Wed Apr 24 09:48:38 +0000 2013"
timest = aTime.to_time.to_i
Test.create({time_stamp: timest})
Run Code Online (Sandbox Code Playgroud)

我看到time_stamp在数据库中存储为String.任何人都可以指示我将时间戳存储为DB中的数字,以便我可以对其执行某些操作.提前致谢.

mic*_*lpm 2

根据这个答案,MongoDB支持的数字类型有:

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)
Run Code Online (Sandbox Code Playgroud)

Mongoid 文档中的这一声明强化了这一点:

Types that are not supported as dynamic attributes since they cannot be cast are:

BigDecimal
Date
DateTime
Range
Run Code Online (Sandbox Code Playgroud)

我不知道你想用这个字段做什么,但如果你真的希望它存储为数字,你必须使用 MongoDB (BSON) 支持的不同数字类型,可能是FloatInteger