Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a single field in MongoDB using Pymongo?

Tags:

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?

like image 542
Kaushik Makwana Avatar asked Feb 02 '16 04:02

Kaushik Makwana


People also ask

How do I select a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I get unique values in PyMongo?

PyMongo includes the distinct() function that finds and returns the distinct values for a specified field across a single collection and returns the results in an array. Parameters : key : field name for which the distinct values need to be found.


2 Answers

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

data = db.author.find_one({'email' : email, 'password' : password}, {'_id': 1})
like image 172
styvane Avatar answered Oct 01 '22 08:10

styvane


it is the best way for avoiding id,

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

now you got ANSWER "{'password': '123123', 'name': 'prakash', 'email': '[email protected]'}"(without id)

like image 42
PrabhuPrakash Avatar answered Oct 01 '22 08:10

PrabhuPrakash