1

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?

2
  • Are you trying to get the string in return or do you have to perform actual MongoDB query? Commented May 31, 2017 at 11:58
  • I have to do a MongoDB query. I need results from the database. Commented May 31, 2017 at 12:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes but the problem is that I don't know how many parameters I have from the beginning. I don't know if i should ma a query on IngredientsHome[1], IngredientsHome[2] and IngredientsHome[3] or just 2 IngredientsHome. If i just loop and make a new query everytime I will end up with multiples duplicates. 1 recipe contains multiples ingredients so the same recipe will come up multiple times.
@NotUser9123 Updated my answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.