簡體   English   中英

Python檢查MongoDB字段是否存在

[英]Python check MongoDB field exists or not

我有兩個集合,一個是存儲如下信息的網站

{
    "_id" : ObjectId("5ac5efd6a37efa4c0e28f5aa"),
    "main_id" : 3,
    "status" : "",
    "website" : "http://test.com",
    "last_access_time" : "2018-04-16 17:49:03",

    "links" : [ 
        {
            "link_id" : "test-1",
            "link" : "test1.html"
        }, 
        {
            "link_id" : "test-2",
            "link" : "test.html"
        }
    ]
}

另一個是website_info ,我想在其中存儲信息,例如:

    {
    "_id" : ObjectId("5ad72ddecf45b60dffcbf9f2"),
    "main_id" : 3,
    "last_access_time" : "2018-04-18 15:37:02",
    "test-1" : {
        "no_of_links" : 55,
        "links_2" : [ 
            {
                "link" : "/home",
                "link_id" : "secnd-1",
            }, 
            {
                "link" : "/login",
                "link_id" : "secnd-2",
            }, 
            {
                "link" : "/services",
                "link_id" : "secnd-3",
            }
        ]
    },
    "test-2" : {
        "no_of_links" : 55,
        "links_2" : [ 
            {
                "link" : "/home",
                "link_id" : "secnd-1",
            }, 
            {
                "link" : "/login",
                "link_id" : "secnd-2",
            }, 
            {
                "link" : "/services",
                "link_id" : "secnd-3",
            }
        ]
    }

}

我正在使用 Python3 和 mongoDB。 在這里,我想檢查 main_id = 3 的website_info中的“link_id”之類的“test-1”字段是否存在。 如果存在,我將更新相同,如果不存在,我想插入新記錄集。 問題是如何檢查website_info集合中的字段“test-1”(這是來自網站集合的值)是否存在。 幫助表示贊賞。

在我的例子中,link_id 在 website_info 集合中是唯一的。 所以不需要檢查 main_id,只檢查 link_id 就解決了我的問題,比如:

    @classmethod 
    def find_link(self, link_id):
        cursor = self.db.collection.find({link_id: {'$exists': True}} ) 
        results = list(cursor) 
        return results

並檢查是否存在,如:

if(len(is_exists)>0):
  #do if exists

暫無
暫無

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

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