隨着$查找,$項目和$匹配正確的組合,你可以在參數加入多發的表。這是因爲他們可以多次鏈接。
第1步:連接所有表
$查找 - 一個用於查詢每個表
$放鬆 - 因爲數據被正確地去歸一化,否則包裹在陣列
Python code ..
db.LeftTable.aggregate([
# connect all tables
{"$lookup": {
"from": "RightTable",
"localField": "ID",
"foreignField": "ID",
"as": "R"
}},
{"$unwind": "R"}
# {"$lookup": {
# "from": "TopTable",
# "localField": "ID",
# "foreignField": "ID",
# "as": "T"
# }},
# {"$unwind": "T"},
])
第2步:定義所有條件語句
$項目:在這裏定義的所有條件語句,加上所有的變量,你想選擇。
Python代碼..
db.LeftTable.aggregate([
# connect all tables
{"$lookup": {
"from": "RightTable",
"localField": "ID",
"foreignField": "ID",
"as": "R"
}},
{"$unwind": "R"},
# {"$lookup": {
# "from": "TopTable",
# "localField": "ID",
# "foreignField": "ID",
# "as": "T"
# }},
# {"$unwind": "T"},
# define conditionals + variables
{"$project": {
"midEq": {"$eq": ["$MID", "$R.MID"]},
# "midGt": {"$gt": ["$MID", "$T.MID"]},
"ID": 1, "MOB": 1, "MID": 1
}}
])
第3步:加入所有的條件
$匹配 - 使用OR或等可以有這些倍數加入的所有條件。
$項目:取消定義的所有條件語句
Python代碼..
db.LeftTable.aggregate([
# connect all tables
{"$lookup": {
"from": "RightTable",
"localField": "ID",
"foreignField": "ID",
"as": "R"
}},
{"$unwind": "$R"},
# {"$lookup": {
# "from": "TopTable",
# "localField": "ID",
# "foreignField": "ID",
# "as": "T"
#}},
#{"$unwind": "$T"},
# define conditionals + variables
{"$project": {
"midEq": {"$eq": ["$MID", "$R.MID"]},
# "midGt": {"$gt": ["$MID", "$T.MID"]},
"ID": 1, "MOB": 1, "MID": 1
}},
# join all conditionals
{"$match": {
"$and": [
{"R.TIM": {"$gt": 0}},
{"MOB": {"$exists": True}},
{"midEq": {"$eq": True}},]
}},
# undefine conditionals
{"$project": {
"midEq": 0,
# "midGt": 0
}}
])
差不多的表,條件任意組合,並加入可以通過這種方式來完成。
這可能是一個很好的起點:https://www.mongodb.com/blog/post/joins-and-other-aggregation-enhancements-coming-in-mongodb-3-2-part-1-of -3-introduction – Barney
已經引用了幫助我構建上述查詢部分的帖子。這篇文章並沒有提到我正在尋找的多個鍵。 –
這是不可能在mongoDB? –