【问题标题】:How to take the value of a specific key in MongoDB with Python如何使用 Python 获取 MongoDB 中特定键的值
【发布时间】:2019-08-04 01:22:27
【问题描述】:

我确定这很简单,但我需要从键值对中提取一个值来检查它是否与会话中的用户名匹配。 (我正在使用 pymongo)

其中一个 MongoDB 对象的示例如下所示('jam_or_event' 是集合名称):

_id: ObjectId("5d44545037b30613b88ae587")
jam_title: "Test Jam 2"
genre: "Rock"
date_of_jam: "2 August, 2019"
jam_location: "Test Address 2"
jam_county: "Bristol"
jam_member_1: "TestUser2"
member_instrument_1: "Drums"
jam_notes: "Test 2"
jam_owner: "TestUser2"

值将对象更改为对象,但我希望能够从当前选定的对象中提取 jam_owner 值,并询问它是否与当前登录用户的用户名相同。如果它们匹配,它们将对页面拥有更多权限。

这是python函数的代码:

@app.route('/edit_jam/<jam_id>', methods=['POST', 'GET'])
def edit_jam(jam_id):
    user_logged_in = 'username' in session
    the_jam =  mongo.db.jam_or_event.find_one({"_id": ObjectId(jam_id)})
    username=session['username']

    if request.method == 'POST':
        if user_logged_in:
            jams = mongo.db.jam_or_event
            jams.update( {'_id': ObjectId(jam_id)},
            {
                'jam_title':request.form.get('jam_title'),
                'genre':request.form.get('genre'),
                'date_of_jam': request.form.get('date_of_jam'),
                'jam_location': request.form.get('jam_location'),
                'jam_county':request.form.get('jam_county'),
                'jam_member_1':request.form.get('jam_member_1'),
                'member_instrument_1':request.form.get('member_instrument_1'),
                'jam_notes':request.form.get('jam_notes'),
            })
            return redirect(url_for('get_jams'))
    return render_template('editjam.html',
        jam=the_jam,
        instruments=mongo.db.instruments.find(),
        counties=mongo.db.counties.find(),
        username=session['username'])

然后我想说,在html中

{% if jam_owner == username %}
xyz
{% endif %}

【问题讨论】:

    标签: python python-3.x mongodb key-value


    【解决方案1】:

    好吧,我不确定你是不是这个意思,但我希望我理解正确,尽管问起来似乎很简单。

    好的,所以这段代码正在从 Mongo db 返回对象:

    the_jam =  mongo.db.jam_or_event.find_one({"_id": ObjectId(jam_id)}) # so the_jam will hold the Object (Dictionary) from Mongodb.
    

    您可以访问您的 jam_owner 或其他任何名称:

    the_jam[key] # as key you want to get jam owner value I think so it will be the_jam["jam owner"]
    

    因为你在用户名变量中有用户的名字,你可以比较它:

    if username == the_jam["jam owner"]:
    # ....
    

    【讨论】:

    • 对不起,蛇怪,我不认为我解释得很好。这只是一个示例,因此它可以是具有所有不同值的任何对象,我需要从本质上找出 jam_owner 的值。
    • 你想要的输出是什么?
    • 我希望从本质上说:如果用户名 == jam_owner: xyz
    • 我不明白。您能否修改问题并描述您想要的输出以及您的数据结构等。?这将帮助您更快地得到答案
    • 刚刚更新,希望更有意义,感谢您查看这个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    相关资源
    最近更新 更多