2013-04-24 56 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