How to select a single field in MongoDB using Pymo

2019-01-19 02:05发布

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?

3条回答
We Are One
2楼-- · 2019-01-19 02:39

You need to pass the second object in your query. First parameter is a select clause, whereas the second one is a projection.

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

查看更多
放荡不羁爱自由
3楼-- · 2019-01-19 02:45

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': 'prakashprabhu48@gmail.com'}"(without id)

查看更多
ら.Afraid
4楼-- · 2019-01-19 02:55

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

data = db.author.find_one({'email' : email, 'password' : password}, {'_id': 1})
查看更多
登录 后发表回答