Kaushik Makwana Kaushik Makwana - 1 month ago 8
Python Question

How to select a single field in MongoDB using Pymongo?

I'm trying to find a record within MongoDB, and filter

_id
from the result.

Here is my code:

#app.py
@app.route('/login', methods = ['GET', 'POST'])
def login():
if request.method == "POST":
password = request.form.get('password')
email = request.form.get('email')
db = get_db()
data = db.author.find_one({'email' : email, 'password' : password})
print(data)
return 'data'
else:
return render_template('login.html')


Output:

{'password': '123123', 'name': '<my_name>', 'email': '<my_email>', '_id': ObjectId('<an_object_id_string>')}


How do I filter the
_id
field from the output?

Answer

You need to specify the field you want to return using projection.

data = db.author.find_one({'email' : email, 'password' : password}, {'_id': 1})
Comments