I am working on a project, to query for a particular document in mongodb database in pymongo and showing it on flask app.
Here is the Code:
from flask import Flask
from flask_pymongo import PyMongo
import pymongo
import json
app = Flask(__name__)
@app.route("/")
def home_page():
return "hello world"
@app.route("/user/<string:phone>")
def user_profile(phone):
client = pymongo.MongoClient("mongodb+srv://Diligent:[email protected]/test")
db = client["MyDatabase"]
col = db["UserID"]
for x in col.find({"Contact No": phone}, {"_id":0, "UserID": 1, "User": 1, "Contact No": 1, "Designation": 1 }):
print(x)
return x
So when I enter input like "http://127.0.0.1:5000/user/phone=9331828671" in flask App.py
I get errors like:
UnboundLocalError: local variable 'x' referenced before assignment.
So How should I solve this to get detailed data for particular queries?
I really appreciate any help you can provide.
With the for-loop you have specified, you are going through an iterable, retrieving every matching
xand printing this. This value x is discarded directly after this for-loop.Now it's up to you what you want to get. If you, for example, want to retrieve the last matching
x, try this: (This returnsnullif no x matches)If you want all matching
x's, try this: (this returns[]if no x matches)PS: watch your indentation, it is python you are working in.