[英]How to pass the value of a variable into a mongo query?
The following mongo query works correctly: db.data.find({"data.id": "5" })
以下mongo查询可以正常工作:
db.data.find({"data.id": "5" })
I want to pass the value of a variable for an argument list to the query in a python program: 我想将参数列表的变量值传递给python程序中的查询:
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.dhlab
data=db.data
for data in db.data.find({"data.id":'"' $id '"'}):
print data
I tried the following for db.data.find({"data.id":id})
without success: /"id/", '"'id'"', /"$id/"
我尝试对
db.data.find({"data.id":id})
但未成功: /"id/", '"'id'"', /"$id/"
How can I fix this? 我怎样才能解决这个问题?
Did you mean this? 你是这个意思吗
result = db.data.find({"data.id": {$in: [1,2,3,5]} })
for data in result:
print(data) // will print all 'data' document whith that id
You can replace [1,2,3,5] whith your own values or a variable. 您可以用自己的值或变量替换[1,2,3,5]。 For example:
例如:
range(1,5) # is equal to [1,2,3,4]
[1,2,3] # it takes ids equal to 1,2 or 3
We could consider this situation ( we want to use just even numbers ): 我们可以考虑这种情况(我们只想使用偶数):
list = []
numbers = range(1,100)
for number in numbers:
if number % 2 == 0
list.append(number)
result = db.data.find({"data.id": { $in: list } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.