title: Implementing MongoDB search engine API in Flask
body: <p>I am new to MongoDB and I am trying to build a simple search page using MongoDB in Flask. </p>
  
  <p>I have a <strong>restaurants.json</strong> ingested into MongoDB: </p>
  
  <pre><code>{ "_id" : ObjectId("57506d62f57802807471dd42"), "name" : "456 Cookies Shop", "contact" : { "phone" : "604-555-0149", "email" : "456CookiesShop@example.org", "location" : [ -73.8850023, 40.7494272 ] }, "stars" : 4, "categories" : [ "Bakery", "Cookies", "Cake", "Coffee" ] }
  { "_id" : ObjectId("57506d62f57802807471dd28"), "name" : "XYZ Bagels Restaurant", "contact" : { "phone" : "435-555-0190", "email" : "XYZBagelsRestaurant@example.net", "location" : [ -74.0707363, 40.59321569999999 ] }, "stars" : 4, "categories" : [ "Bagels", "Sandwiches", "Coffee" ] }
  { "_id" : ObjectId("57506d62f57802807471dd44"), "name" : "XYZ Steak Buffet", "contact" : { "phone" : "229-555-0197", "email" : "XYZSteakBuffet@example.org", "location" : [ -73.9799932, 40.7660886 ] }, "stars" : 3, "categories" : [ "Steak", "Salad", "Chinese" ] }
  </code></pre>
  
  <p><strong>search.py</strong>:</p>
  
  <pre><code>from flask import Flask, render_template, url_for, request, session, redirect, jsonify
  import json
  from flask import Flask
  from flask_pymongo import PyMongo
  from pymongo import MongoClient
  
  app = Flask(__name__)
  client = MongoClient('localhost',27017)
  mongo = PyMongo(app)
  db = client.dummy
  collection = db.restaurants
  
  @app.route('/search', methods = ['GET'])
  def search():
      search = mongo.db.collection
      output = []
      for q in search.find():
          output.append({'name' : q['name'], 'categories' : q['categories']})
      return jsonify({'result' : output})
  
  @app.route('/search/&lt;name&gt;', methods = ['GET'])
  def search_by_keyword(name):
      search_by_keyword = mongo.db.collection
      q = search_by_keyword.find_one({'name' : name})
      output = {'name' : q['name']}
  
      return jsonify({'results' : output})
  
  if __name__ == '__main__':
  app.run(debug=True)
  </code></pre>
  
  <p><strong>search.html</strong>: </p>
  
  <pre><code>{% from "_formhelpers.html" import render_field %}
  &lt;form method=post&gt;
    &lt;dl&gt;
      {{ render_field(form.select) }}
      &lt;p&gt;
      {{ render_field(form.search) }}
    &lt;/dl&gt;
    &lt;p&gt;&lt;input type=submit value=Search&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p><strong>forms.py</strong>:</p>
  
  <pre><code>from wtforms import Form, StringField, SelectField
  
  class SearchForm(Form):
      choices = [('name', 'name'),
             ('categories', 'categories')]
      select = SelectField('Search:', choices = choices)
      search = StringField('')
  </code></pre>
  
  <ul>
  <li>How do I make a keyword search to search on all Mongo fields, not just the one I specified (name)? </li>
  <li>How do I make json output file to be posted as a search result in html?</li>
  </ul>