【问题标题】:Unable to retrieve data from MongoDB if same collection has different elements from python如果同一集合具有来自 python 的不同元素,则无法从 MongoDB 检索数据
【发布时间】:2020-11-24 04:51:53
【问题描述】:

我在 MongoDB 集合中有一组 JSON,这些 JSON 由 webhook 接收,我无法控制它,一个集合的元素不会与另一个集合相同。我能够检索那些对所有其他数据具有相同键的元素。但我需要检索这些数据,无论它是否存在于其他文档中。附上 MongoDB 中存在的值的图片。

我正在使用下面的代码将 webhook 插入到 MongoDB

@app.route('/webhook', methods=['POST', 'GET'])
def respond():
    collection10 = db['webhooks']
    a = request.get_json()
    print(a)
    collection10.insert_many(a)
    return render_template("signin.html")

假设我尝试检索“_id”,我可以轻松检索,因为两个数据都有“_id”。但是,如果我尝试检索那些存在于一个中而不存在于另一个中的元素,则会出现错误。

我正在使用此代码来检索元素:

@app.route('/webhookdisplay', methods=['POST', 'GET'])
def webhooksdis():
    collection10 = db['webhooks']
    for i in collection10.find({}):
        posts = i['name']
        print(posts)
    return render_template("webhooks.html", posts = posts)

上面的代码出错了

KeyError: '名称'

如果我以与上述相同的方式检索“_id”,它将被检索。

预期结果:我需要检索嵌套数据,无论它是否存在于其他数据中。如果有任何其他方法可以在 HTML 页面中以表格的形式显示特定数据,那就太好了

目的一旦我得到个人数据,我可以在前端使用 Jinja 以表格的形式呈现相同的数据

【问题讨论】:

    标签: python python-3.x mongodb flask pymongo


    【解决方案1】:

    如果您不确定返回的记录是否包含特定键,那么您应该使用built-in .get() function.,如果该键不存在,则默认返回 None,这与使用方括号引用不同。这将避免您看到的 KeyError 异常。

    posts = i.get('name')
    
    if posts is None:
        # Handle logic if name doesn't exist
    

    编辑:如果您需要嵌套字段:

    name = i.get('data', {}).get('geofence_metadata', {}).get('name')
    

    【讨论】:

    • 通过上述方式,我只能访问主要元素。如果我想访问嵌套元素怎么办,即在上述情况下,我想访问 [data][geofence_metadata][name] 的值。如果只有 2 个元素嵌套,即 for i in collection.find({}): i['location']['coordinates']
    • 如果是其他问题,请使用相关标签打开另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2015-07-30
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多