user1513388
user1513388

Reputation: 7451

Pymongo find if value has a datatype of NumberLong

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.

Upvotes: 0

Views: 4653

Answers (2)

Sebastian
Sebastian

Reputation: 17443

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}

Upvotes: 1

Malcolm Murdoch
Malcolm Murdoch

Reputation: 1085

You can use $type: http://docs.mongodb.org/manual/reference/operator/query/type/

INT is 16, BIGINT is 18

Upvotes: 0

Related Questions