我在 mongodb 中有三個集合,我想加入它們以獲取一些資料。這是我的架構:
//user collection
{
"_id": "616b429e0de99f6f74f911b9",
"name": {
"firstname": "Kisko",
"lastName": "Barrisson"
}
}
//Devices collection
{
_id:"616b52453dcacbf8a3f989a8",
user:"616b429e0de99f6f74f911b9",
name:"driver",
data:[{X:123,Y:200},{X:124,Y:300}]
}
//locations collection
{
"_id": {
"$oid": "6193b7a7751212e5358b481a"
},
"X": 123,
"Y":200,
"adresse":"My current adresse"
}
我想這樣做:"Select l.adresse,d.name,u.name from user u LEFT JOIN devices d ON u._id=d.user LEFT JOIN locations l ON l.X = d.X AND L.Y=d.Y WHERE u._id=616b429e0de99f6f74f911b9"。我怎么能用貓鼬做到這一點。請幫幫我!
uj5u.com熱心網友回復:
詢問
- 從設備開始,匹配用戶
- 展開資料
(為了使連接更容易,將連接欄位放在陣列中會使事情變得更難) - 加入用戶(SQL 之類的加入)
- 加入地點
*您可以避免替換根,但它們使每個階段的結果看起來更簡單
*為了提高性能,在devices.user 和X、Y 位置上創建索引,您還需要MongoDB 5,以便在第二個管道查找中使用索引
測驗代碼在這里
devices.aggregate(
[{"$match": {"user": "616b429e0de99f6f74f911b9"}},
{"$unwind": {"path": "$data"}},
{"$lookup":
{"from": "users",
"localField": "user",
"foreignField": "_id",
"as": "joined__"}},
{"$unwind": {"path": "$joined__"}},
{"$replaceRoot":
{"newRoot": {"$mergeObjects": ["$joined__", "$$ROOT"]}}},
{"$lookup":
{"from": "locations",
"let": {"x": "$data.X", "y": "$data.Y"},
"pipeline":
[{"$match":
{"$expr":
{"$and": [{"$eq": ["$$x", "$X"]}, {"$eq": ["$$y", "$Y"]}]}}}],
"as": "joined"}},
{"$unwind": {"path": "$joined"}},
{"$replaceRoot": {"newRoot": {"$mergeObjects": ["$joined", "$$ROOT"]}}},
{"$group":
{"_id": "$user",
"data":
{"$push":
{"adresse": "$adresse", "X": "$X", "Y": "$Y", "name": "$data.name"}},
"userName": {"$first": "$name"}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360065.html
上一篇:換新護照前如何檢查密碼是否匹配
