Reputation:
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?
Upvotes: 2
Views: 666
Reputation: 473873
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})
Upvotes: 4