简体   繁体   中英

Pymongo when using find_one does not return value if number casted as string

I have a collection object created the following way:

from pymongo import MongoClient
collection=MongoClient(r'mongodb://localhost:27017/')['test']['cars']

collection.insert({"_id":30,"model":"Audi"})

The find it self returns:

 collection.find({'_id':30})
 {'_id': 30, 'model':'Audi'}

The find_one with integer:

collection.find_one({'_id':30})
{'_id': 30, 'model':'Audi'}

But the find_one with a string :

collection.find_one({'_id':"30"})
None

Is there a workaround or it is supposed to be like that?

Does it matter the data type of how the field is created?

Even if the equivalent of casting the string as int it's the same.

As far as MongoDB is concerned, 30 and "30" are different. The database doesn't mind too much which one you use, and won't (by default) check, so you will need to ensure the types match in your querires.

If this is a problem them you can add collection level validation to specify expected the BSON types for each field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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