简体   繁体   中英

Mongo query in python if I use variable as value

Am trying to find documents from the mongo collection using the following query. db.collection_name.find({"id" : Id}) where Id is the variable am getting as input. But it doesn't work. If I hard code the value like this db.collection_name.find({"id" : "1a2b"}) it works. "id" is of string type and am using pymongo to access mongo DB.

code :

client = MongoClient("localhost:27017")                
db = client['sample_database']
Id = raw_input("enter id") 
cursor = db.collection_name.find({"id" : Id})

Try str();

Id = str(raw_input("enter id"))
cursor = db.collection_name.find({"id" : Id})

This may help you..in python3 it is working..

Id = raw_input("enter id: ") 
cursor = db.collection_name.find({"id" : Id})
for i in cursor:
    print(i)

there is no require to convert raw_input() to string,Because raw_input() is already get input from user as string..

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