簡體   English   中英

MongoDB如何深入接入

[英]How to access MongoDB in-depth

我有以下問題。 我似乎沒有弄清楚如何訪問警告字段中的“UID”值。 我想遍歷文檔中的每個值,並訪問每個現有的 UID 以檢查隨機生成的 UID 是否已經存在。 老實說,我正因此而精神崩潰,我似乎無法弄清楚

這是我的 MongoDB 結構的樣子: https://i.imgur.com/sfKGLnf.png

在 python 代碼中獲得 object 之后,警告將是一個列表 - 因此您可以遍歷warnings列表中的文檔並訪問其UID密鑰

已編輯評論代碼:我們可以通過使用find和空查詢字典來獲取集合中的所有文檔,盡管我已經在下面鏈接了 find 上的文檔。 由於您的文檔結構似乎有一個隨機數作為鍵,然后是一個嵌入式文檔,我們在文檔中找到了不是_id的鍵。 可能只有一把鑰匙,但我不想假設。 如果我們的嵌入式文檔中有一個warnings鍵,我們將遍歷每個警告並將“UID”添加到我們的warning_uids列表中。

# this is your collection object
mod_logs_collection = database["modlogs"]

all_mod_docs = mod_logs_collection.find({})

warning_uids = []
for doc in all_mod_docs:
    # filter all the doc keys that aren't the default `_id`
    doc_keys = [key for key in doc.keys() if key != "_id"]

    # not sure if it's possible for you to have multiple keys in a doc 
    # with this structure but we'll iterate over the top-level doc keys
    # just in case
    for key in doc_keys:
        sub_doc = doc[key]
        if warnings := sub_doc.get("warnings")
            for warning in warnings:
                warning_uids.append(warning["UID"])
                print(warning["UID"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM