How to select a single field in MongoDB using Pymongo?

I am trying to find an entry in MongoDB and filter the _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 to filter the _id field on output?

+5
source share
3 answers

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

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

You need to pass the second object to your request. The first parameter is the select clause, while the second is the projection.

See the MongoDB docs for more details: https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/

+2
source

this is the best way to avoid id,

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

now you have ANSWER "{'password': '123123', 'name': 'prakash', 'email': ' prakashprabhu48@gmail.com '}" (without id)

+2
source

Source: https://habr.com/ru/post/1242066/


All Articles