简体   繁体   English

pymongo查询中的long或int是否必须与mongodb中的数字类型匹配?

[英]Does long or int in pymongo queries have to match the number type in mongodb?

I can't find much of an indication in neither the pymongo documentation or the mongodb documentation. 我在pymongo文档或mongodb文档中都找不到太多的迹象。 I'm currently working with python3, and I have one program inserting data and another program that queries it. 我目前正在使用python3,我有一个程序可以插入数据,而另一个程序可以查询数据。

Basically, if one program inserts data as a BSON long type (64 bit), can another program query that data with a 32 bit int? 基本上,如果一个程序将数据作为BSON long类型(64位)插入,那么另一个程序可以查询32位int的数据吗?

For example, where I write data. 例如,我在哪里写数据。

from bson.int64 import Int64
...
coll.insert({'myval': Int64(100)})

And where I read data. 以及我在哪里读取数据。

coll.find({'myval': int(100)})

Does this work regardless of how big the int is? 不管int有多大,这都行得通吗? Even ignoring if python3 stores the int as a 64 bit? 甚至忽略python3是否将int存储为64位?

You don't have to manually cast your number to bson.int64 on writing; 您不必在写作时将您的号码手动转换为bson.int64; pymongo will take care of this automatically. pymongo将自动处理此问题。

Yes, you can read data with: 是的,您可以通过以下方式读取数据:

coll.find({'myval': int(100)})

or simpler: 或更简单:

coll.find({'myval': 100})

The distinction between int64 and int32 in MongoDB is more about BSON storage size. MongoDB中int64和int32之间的区别更多是关于BSON存储大小。 You can query with either type: 您可以使用以下任一类型进行查询:

Python 3.3.5 (default, Jan 29 2015, 02:00:04) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> c = pymongo.MongoClient()
>>> from bson.int64 import Int64
>>> c.test.int64.insert_one({'int64': Int64(2 ** 32)})
<pymongo.results.InsertOneResult object at 0x7f6ece3f43c0>
>>> c.test.int64.find_one({'int64': int(2 ** 32)})
{'int64': 4294967296, '_id': ObjectId('554fa762fa5bd8782e1698ce')}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM