Python Forum

Full Version: find a string in a field in MongoDB
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello coders,

I'm a student and I've almost finished my project for my course. As last thing I added a small search bar in the index.html in order to submit an ingredient, and through search.html I will get all the recipes with that ingredient. This is the little form:

        <form id="search-form" action="{{ url_for('search', mysearch=bar) }}" method="POST">
          <input id="search-box" name="bar" type="text" placeholder="Search by any ingredient!" />
          <input id="search-btn" value="" type="submit" />
        </form>
In the main.py I added the following python code:


@app.route('/search/<mysearch>')
def search(mysearch):
    query={"ingredients": { "$regex": "/*mysearch*/i" }}
    return render_template("search.html", recipes=mongo.db.recipes.find(query))
I cannot really understand well the MongoDB documentation, I tried many ways but when I look for a word I just get:
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

I think there is something wrong in both my code in Python and the small form, since the page search.html is well done.

Could you please help me and tell me what I'm doing wrong? Thank you very much!!!

@app.route('/search/<mysearch>')
def search(mysearch):
    query={"ingredients": { "$regex": mysearch }}
    return render_template("search.html", recipes=mongo.db.recipes.find(query))
I changed it in this way, so now if I got to the address bar and I write http://127.0.0.1:5000/search/chicken I get all the recipes with chicken, but if I use the search bar I get the same error.
I have almost solved, just I cannot manage to look for the word with case insensitive, if I write parmesan it finds it, if I write ParMeSan it doesn't. Any Idea?

@app.route('/search', methods=["POST"])
def search():
    if request.method == "POST":
        data = request.form.to_dict()
        keyword = str(data['mysearch'])
        query={"ingredients": { "$regex": keyword }}
    return render_template("search.html", recipes=mongo.db.recipes.find(query))
I would recommend forcing everything to be lowercase. You could also look into casefold.