2013-04-24 121 views
13

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

class Test 
    include Mongoid::Document 
    field :time_stamp, type: BigDecimal 
end 

而下面是我用来创建文档代码:

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

我看到TIME-STAMP存储为字符串在数据库。任何人都可以指示我将时间戳存储为数据库中的数字,以便我可以对其执行一些操作。提前致谢。

+2

要存储时间戳,您需要'include Mongoid :: Timestamps' ..这将为您的文档创建:created_at&:updated_at字段。不知道你的领域':time_stamp'是如何神奇地用时间字符串填充的。 – brayne 2013-04-24 22:25:53

+0

这可能是Mongoid的MongoDB驱动程序Moped中的一个错误。你可以通过在mongo shell中查询发布你可以看到的数据吗? 如果你真的只想存储时间戳,你可以将字段类型设置为'Time'而不是'BigDecimal'。 – davogones 2013-04-27 05:18:16

+0

@senthil,只是试图重现和调出价值(time_stamp)被存储为一个数字。 mongoid(3.0.23) – ted 2013-05-20 10:29:25

回答

2

this answer,由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) 

被这句话在Mongoid documentation钢筋:

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

BigDecimal 
Date 
DateTime 
Range 

我不知道你想用的东西该字段,但如果您确实希望将其存储为数字,则必须使用MongoDB(BSON)支持的不同数字类型,可能为FloatInteger

+0

这不相关,因为'field:time_stamp,type:BigDecimal'确实指定了支持的字段类型BigDecimal。在存储到MongoDB之前,它应该将其转换为整数。 – davogones 2013-04-27 05:17:09

+1

我认为** double **比** int32 **更有意义** ** decimal,但对于** unbounded decimal **则不够用(因此它必须存储为其他内容,比如**串**)。如果您的字段可以表示为MongoDB ** int32 **或MongoDB ** int64 **,则将其设为Mongoid ** Integer **,而不是Mongoid ** BigDecimal **。 – michelpm 2013-04-27 12:03:53