如果同一集合具有来自 python 的不同元素,则无法从 MongoDB 检索数据

Unable to retrieve data from MongoDB if same collection has different elements from python

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

中存在的值的图片

我正在使用以下代码将 webhooks 插入到 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: 'name'

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

预期结果: 我需要检索嵌套数据,无论它是否存在于其他数据中。如果有任何其他方法可以在 HTML 页面

中以 table 的形式显示特定数据,那就太好了

目的 一旦我获得个人数据,我可以使用 Jinja 以 table

的形式在前端呈现相同的数据

如果您不确定返回的记录是否包含特定键,那么您应该使用 built-in .get() function.,默认情况下 returns None 如果键不包含present,不像使用方括号引用。这将避免您看到的 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')