[英]Python check MongoDB field exists or not
I have two collections one is websites which stores information like:我有两个集合,一个是存储如下信息的网站:
{
"_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"
}
]
}
And another is website_info in which I want store info like:另一个是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",
}
]
}
}
I am using Python3 and mongoDB.我正在使用 Python3 和 mongoDB。 Here I want to check the field like "link_id" which is "test-1" in the website_info for main_id = 3 exists or not.
在这里,我想检查 main_id = 3 的website_info中的“link_id”之类的“test-1”字段是否存在。 If it is exists I will update for same, if does not exists I want to insert new record set.
如果存在,我将更新相同,如果不存在,我想插入新记录集。 The thing is how to check whether field "test-1" (which is the value from websites collection) in website_info collection exists or not.
问题是如何检查website_info集合中的字段“test-1”(这是来自网站集合的值)是否存在。 Help is appreciated.
帮助表示赞赏。
Here in my case, link_id will be unique in website_info collection.在我的例子中,link_id 在 website_info 集合中是唯一的。 So no need to check for main_id, only checking for link_id solved my issue, like:
所以不需要检查 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
And check for exists like:并检查是否存在,如:
if(len(is_exists)>0):
#do if exists
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.