2

I want to query different fields on MongoDB from Python, like in an advanced search.

Keeping the example simple with just one field, if I query {'Title': /my string/} manually on Mongo I get the expected results.

On Python I am doing the following:

query = {}
args = request.form
for arg in args:
  key = "{0}".format(arg)
  if args[arg] != "":
    query[key] = "/" + args[arg].lower() + "/"

However, the query is like this (note the quotes):

{'Title': '/my string/'}

So I don't get any results. How can I implement the right query?

1 Answer 1

4

Make a list:

conditions = [{field: {"$regex": value.lower()}} for field, value in args.items()]

Then, join the conditions with $or or $and (depending on how do you want to apply them):

db.col.find({"$or": conditions})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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