Reputation: 28
I am trying to make query in mongodb where I don't know how many variables I have from the beginning. You get an array with variables(strings) and then mongo should return via the $or operator so there are no duplicates.
def findRecipes(IngredientsHome):
#Query and return all the alternatives
arrayCompleteSearch = [];
if len(IngredientsHome) > 1:
#theHardStuuff
#Create the query based on ingredientsarray
argsCount = len(IngredientsHome)
argsFunction = "";
for i in range(0, len(IngredientsHome)):
if i < (len(IngredientsHome)-1):
argsFunction += ("{"+'"_Ingredients":' + '"' + IngredientsHome[i] + '"' "}, ")
else:
argsFunction += "{" + '"_Ingredients":' + '"' + IngredientsHome[i] + '"' + "}"
if I then do like this
print("coll.find({" + '$or' + ':' + '[' + argsFunction + ']' "})")
the commandline will print(not execute) the command i want to do in mongodb but I don't know how to make it work in mongo and return the results to an array. I am using pymongo and there i don't if it's possible to use a string as a full query. In sql I could put the whole "query" as a string "SELECT * FROM ..."
while pymongo need : outside the string, more like coll.find({"String":"String"})
. Is there a similar method or another way to make this query when I don't know how many expressions I have from the beginning in my mongodb query?
Upvotes: 1
Views: 1603
Reputation: 6041
Instead of constructing your query as a string, use PyMongo methods to query your database, for example:
coll.find({'_Ingredients': IngredientsHome[i]})
or you can pass the Python list and use $in
in your query:
coll.find({'_Ingredients': {'$in': IngredientsHome}})
Read more about how to use PyMongo here.
Upvotes: 1