首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pymongo 64位无符号整数

pymongo 64位无符号整数
EN

Stack Overflow用户
提问于 2012-01-11 18:37:52
回答 1查看 3.6K关注 0票数 1

我正在尝试使用pymongo在mongodb中插入一个64位无符号整数。该整数是CRC64算法的输出。我试着这样做:

代码语言:javascript
复制
long(crc64(unicode(kw).encode('unicode-escape'))))

如果我把它插入到mongodb中,它会开始抱怨mongodb只支持64位整数。接下来,我尝试将其转换为带符号的64位int,如下所示:

代码语言:javascript
复制
ctypes.c_int64(crc64(unicode(kw).encode('unicode-escape')))).value

mongodb不再抱怨int的大小,但当我查看mongodb中的数据时,我得到了这样的结果:

代码语言:javascript
复制
{
    "_id" : {
        "floatApprox" : -5307924876159732000,
        "top" : 3059119730,
        "bottom" : 2651469802 },
    "keyword" : "redacted",
    "normal_hash" : { 
        "floatApprox" : -671156942315906300,
        "top" : 4138701393,
        "bottom" : 549001936
    } 
}

这里发生了什么事?有没有办法把64位的int作为一个int放入db中(不管它是有符号的还是无符号的)。

EN

回答 1

Stack Overflow用户

发布于 2012-01-11 19:29:52

MongoDB使用BSON存储数据,BSON规范规定64位整数是有符号的。

64位机器上的示例会话,64位mongo v2.0.1,python 2.6.5:

代码语言:javascript
复制
>>> 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}
>>> 

并运行此脚本:

代码语言:javascript
复制
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)))

打印:

代码语言:javascript
复制
crc type: <type 'int'>

在mongo shell中:

代码语言:javascript
复制
> db.foo.findOne()
{ "_id" : 1, "crc64" : NumberLong("9007199254740992") }
> 
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8817856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档