Mongo query in python if I use variable as value

守給你的承諾、 提交于 2019-12-24 17:05:06

问题


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})

回答1:


Try str();

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



回答2:


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..



来源:https://stackoverflow.com/questions/37707033/mongo-query-in-python-if-i-use-variable-as-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!