Search code examples
pythonmongodbflaskpymongo

How can I filter MongoDB Database from Pymongo in Flask App?


I am trying to query my database passing as a parameter a string. Some days ago it worked, but suddenly it stopped working. Is there something wrong I am missing?

class Hotel(Resource):
      
  def get(self, cityName):
  
      docs_list  = list(client['mongodbhotels']['wheather_conditions'].find( 
        filter = {
          'name': { "$eq" : cityName} 
          },
        allow_partial_results = True )
        )

      json_response = json.dumps(docs_list, default=json_util.default)
      return json.loads(json_response)

api.add_resource(HotelList, '/')
api.add_resource(Hotel, '/<string:cityName>')


if __name__ == '__main__':
    app.run(debug=True)

I am expecting a url like this with my parameter (city name) http://127.0.0.1:5000/Madrid

This query was working but now it returns an empty value


Solution

  • Have you tried this ?

    class Hotel(Resource):
          
      def get(self, cityName):
      
          docs_list  = list(client['mongodbhotels']['wheather_conditions'].find( 
            filter = {
              'name': cityName
              },
            allow_partial_results = True )
            )
    
          json_response = json.dumps(docs_list, default=json_util.default)
          return json.loads(json_response)
    
    api.add_resource(HotelList, '/')
    api.add_resource(Hotel, '/<string:cityName>')
    
    
    if __name__ == '__main__':
        app.run(debug=True)```