[英]checking if a value exists in mongodb collection using pymongo
我有以下格式的 mongo db 表
[{"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()
這樣的游標
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.