简体   繁体   中英

How to pass the value of a variable into a mongo query?

The following mongo query works correctly: 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:

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/"

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

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