使用pymongo检查mongodb collection中是否存在一个值



我有一个如下格式的数据库表

[{"url":"www.example1.com", "name":"hans","age":30},
{"url":"www.example2.com", "name":"x","age":34},
{"url":"www.example3.com", "name":"y","age":35},
{"url":"www.example4.com", "name":"z","age":36},
{"url":"www.example5.com", "name":"b","age":37}]

我有两个表,我需要在两个if条件下检查。我是这样做的

val = "www.example1.com"
if list(table1.find({"url": {"$eq": val}})):
print("exist in table 1")
if list(table2.find({"url": {"$eq": val}})):
print("exist in table 2")
else:
print("not exist in table 2")
else:
print("not exist in table 1")

这给了我正确的回应,但似乎需要更多的时间来做检查。是否有更好的方法使用pymongo

来执行此查询?

对于MongoDB v4.4+,您可以使用$unionWith。你可能会注意到有两个相同的$match。这是为了减少中间表的大小来提高性能。

db.table1.aggregate([
{
$match: {
"url": {
"$eq": "www.example3.com"
}
}
},
{
"$unionWith": {
"coll": "table2",
"pipeline": [
{
$match: {
"url": {
"$eq": "www.example3.com"
}
}
}
]
}
}
])

这是Mongo游乐场供您参考。

我会用findOne:

val = "www.example1.com"
if table1.find_one({"url": {"$eq": val}}):
print("exist in table 1")
if table2.find_one({"url": {"$eq": val}}):
print("exist in table 2")
else:
print("not exist in table 2")
else:
print("not exist in table 1")

这比find()fine_one()简单得多,如果找到None,返回一个元素,而不是像find()那样的游标

最新更新