2012-01-11 92 views
1

我試圖用pymongo在mongodb中插入一個64位無符號整數。該整數是CRC64算法的輸出。我試圖:pymongo 64位無符號整數

long(crc64(unicode(kw).encode('unicode-escape')))) 

如果我插入到mongodb它開始抱怨只有64位整數是由mongodb支持。接下來,我試圖將其轉換爲一個帶符號64位INT像這樣:

ctypes.c_int64(crc64(unicode(kw).encode('unicode-escape')))).value 

哪種作品,MongoDB的停止抱怨我int的長度,但是當我在MongoDB中的數據看我得到這個:

{ 
    "_id" : { 
     "floatApprox" : -5307924876159732000, 
     "top" : 3059119730, 
     "bottom" : 2651469802 }, 
    "keyword" : "redacted", 
    "normal_hash" : { 
     "floatApprox" : -671156942315906300, 
     "top" : 4138701393, 
     "bottom" : 549001936 
    } 
} 

這是怎麼回事?有沒有什麼辦法把64位整型數據作爲一個整數(不關心它是有符號還是無符號)。

+0

你在32位或64位機器上運行mongo嗎? – milan 2012-01-11 11:08:18

+0

你是否試過將它編碼爲二進制文件? – incognick 2012-03-28 15:26:57

回答

5

MongoDB使用BSON來存儲數據,而BSON規範說64位整數有符號。

在64位機器上的一個簡單的會話,64位蒙戈V2.0.1,蟒蛇2.6.5:

>>> num = long(9007199254740992) 
>>> num 
9007199254740992L 
>>> bson = BSON.encode({"crc64":num}) 
>>> bson 
'\x14\x00\x00\x00\x12crc64\x00\x00\x00\x00\x00\x00\x00 \x00\x00' 
>>> bson_str = bson.decode() 
>>> bson_str 
{u'crc64': 9007199254740992} 
>>> 

和運行此腳本:

db.foo.save({"_id" : 1, "crc64" : long(9007199254740992)}); 

for doc in db.foo.find({"_id" : 1 }): 
    crc = doc["crc64"] 
    print("crc type: " + str(type(crc))) 

打印:

crc type: <type 'int'> 

和來自蒙戈殼:

> db.foo.findOne() 
{ "_id" : 1, "crc64" : NumberLong("9007199254740992") } 
> 
+0

你的長度不夠長。嘗試使用2 ** 64而不是9007199254740992來完成上述操作。它會引發OverflowError,因爲就mongo而言,該數字太大。除非你將它轉換爲int64(已簽名。) – Blubber 2012-01-11 11:41:12

+1

正如我所說,64位數字是有符號的,這意味着[-2^63,2^63-1]範圍,所以你不能有2^64。 9007199254740992肯定不是32位整數。 – milan 2012-01-11 11:48:20