Pymongo 查找值是否具有 NumberLong 数据类型 [英] Pymongo find if value has a datatype of NumberLong

查看:35
本文介绍了Pymongo 查找值是否具有 NumberLong 数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Pymongo 驱动程序,我的文档如下所示:

<代码>{"_id" : ObjectId("5368a4d583bcaff3629bf412"),"book_id" : NumberLong(23302213),"serial_number" : '1122',}

这是可行的,因为序列号是一个字符串:

find_one({"serial_number": "1122"})

然而,这不会:

find_one({"book_id": "23302213"})

显然是因为 book_id 的数据类型为 NumberLong.如何根据这种数据类型执行find方法?

===================================================

更新:

仍然无法让它工作,我只能找到字符串值.任何建议将不胜感激.

解决方案

您需要确保您的数据类型匹配.MongoDB 对类型很严格.执行此操作时:

find_one({"book_id": "23302213"})

您正在向 MongoDB 请求 book_id 等于 "23302213" 的文档.由于您没有将 book_id 存储为 string 类型,而是将其存储为 long 类型,因此查询需要尊重:

find_one({"book_id": long(23302213)})

如果出于某种原因,您的应用程序中有 ID 作为字符串,这也可以:

find_one({"book_id": long("23302213")})

更新

刚刚检查过(MacOS 64 位、MongoDB 2.6、Python 2.7.5、pymongo 2.7),即使提供整数也能正常工作.

集合中的文档(由 Mongo shell 显示):

{ "_id" : ObjectId("536960b9f7e8090e3da4e594"), "n" : NumberLong(222333444) }

python shell 的输出:

<预><代码>>>>collection.find_one({"n": 222333444}){u'_id': ObjectId('536960b9f7e8090e3da4e594'), u'n': 222333444L}>>>collection.find_one({"n": long(222333444)}){u'_id': ObjectId('536960b9f7e8090e3da4e594'), u'n': 222333444L}

I'm using the Pymongo driver and my documents look like this:

{
"_id" : ObjectId("5368a4d583bcaff3629bf412"),
"book_id" : NumberLong(23302213),
"serial_number" : '1122',
}

This works because the serial number is a string:

find_one({"serial_number": "1122"})

However, this doesn't:

find_one({"book_id": "23302213"})

Obviously its because the book_id has a datatype of NumberLong. How can execute the find method based on this datatype?

==================================================

Update:

Still can't get this to work, I can only find string values. Any advise would be much appreciated.

解决方案

You need to ensure your data types are matching. MongoDB is strict about types. When you execute this:

find_one({"book_id": "23302213"})

you are asking MongoDB for documents with book_id equal to "23302213". As you are not storing the book_id as type string but as type long the query needs to respect that:

find_one({"book_id": long(23302213)})

If, for some reason, you have the ID as string in your app this would also work:

find_one({"book_id": long("23302213")})

Update

Just checked it (MacOS 64bit, MongoDB 2.6, Python 2.7.5, pymongo 2.7) and it works even when providing an integer.

Document in collection (as displayed by Mongo shell):

{ "_id" : ObjectId("536960b9f7e8090e3da4e594"), "n" : NumberLong(222333444) }

Output of python shell:

>>> collection.find_one({"n": 222333444})
{u'_id': ObjectId('536960b9f7e8090e3da4e594'), u'n': 222333444L}
>>> collection.find_one({"n": long(222333444)})
{u'_id': ObjectId('536960b9f7e8090e3da4e594'), u'n': 222333444L}

这篇关于Pymongo 查找值是否具有 NumberLong 数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆