2015-09-22 43 views
1

考慮有以下集合:查詢MongoDB的使用pymongo與變量值

db.collection.insert({id:1, value:1}) 
db.collection.insert({id:2, value:2}) 
db.collection.insert({id:3, value:3}) 

現在,我有具有ID列表的文件。我可以讀取文件並將其存儲在變量中。我現在該如何查詢集合來獲取特定ID的詳細信息:

f=open("file.txt") 
for line in f: 
    idTemp=line.strip() 
    db.collection.find_one({"id":idTemp}) #This does not work 

回答

4

id是一個int,但直接從文件中讀取一個字符串。先將其轉換爲int:

idTemp = int(line.strip()) 
+0

謝謝!這是一個愚蠢的錯誤 –

+0

你能幫我這個,http://stackoverflow.com/questions/37707033/mongo-query-in-python-if-i-use-variable-as-value –