简体   繁体   English

如果我使用变量作为值,则在python中进行Mongo查询

[英]Mongo query in python if I use variable as value

Am trying to find documents from the mongo collection using the following query. 我正在尝试使用以下查询从mongo集合中查找文档。 db.collection_name.find({"id" : Id}) where Id is the variable am getting as input. db.collection_name.find({"id" : Id}) ,其中id是作为输入的变量。 But it doesn't work. 但这是行不通的。 If I hard code the value like this db.collection_name.find({"id" : "1a2b"}) it works. 如果我对db.collection_name.find({"id" : "1a2b"})这样的值进行硬编码,则它可以工作。 "id" is of string type and am using pymongo to access mongo DB. “ id”是字符串类型,正在使用pymongo访问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(); 尝试str();

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

This may help you..in python3 it is working.. 这可能会帮助您..在python3中它正在工作..

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.. 不需要将raw_input()转换为字符串,因为raw_input()已作为字符串从用户那里获取输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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