pymongo 64位无符号整数

1 投票
1 回答
3886 浏览
提问于 2025-04-17 09:59

我正在尝试使用pymongo将一个64位无符号整数插入mongodb。这个整数是CRC64算法的输出。我尝试了以下方法:

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

但是当我把这个插入mongodb时,它开始抱怨说mongodb只支持64位整数。接下来,我尝试把它转换成一个有符号的64位整数,像这样:

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

这样做有点效果,mongodb不再抱怨我的整数大小了,但当我在mongodb中查看数据时,我看到的是:

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

这到底是怎么回事?有没有办法把64位整数直接作为整数放入数据库(我不太在乎它是有符号还是无符号)?

1 个回答

5

MongoDB使用BSON格式来存储数据,而BSON的规范说明64位整数是有符号的。

下面是一个在64位机器上,使用64位的MongoDB版本2.0.1,以及Python版本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'>

还有从MongoDB的命令行界面得到的结果:

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

撰写回答