![](/img/trans.png)
[英]How to join three (multipe) collections with $lookup in mongodb?
[英]Outer join in mongodb using $lookup
我有一個頻道集合
{
channel: "Xamper", //unique
subscribers: [
ObjectId("5a934e000102030405000000"),
ObjectId("5a934e000102030405000001"),
ObjectId("5a934e000102030405000002")
]
}
和一個用戶集合
{
_id: ObjectId("5a934e000102030405000000"),
name: "Bradman"
},
{
_id: ObjectId("5a934e000102030405000001"),
name: "Hartin"
},
{
_id: ObjectId("5a934e000102030405000002"),
name: "Migra"
},
{
_id: ObjectId("5a934e000102030405000004"),
name: "Polycor"
}
現在我需要找到頻道名稱"Xamper"
並計算不在subscribers
數組中的subscribers
所以輸出將是
{
channel: "Xamper",
unSubscribers: 1
}
類似於 SQL 的外部排除連接
您可以在 3.6 中使用以下管道。
$lookup
使用管道將 Channels 集合加入到訂閱者的 Users 集合中
$count
和$not
$in
將訂閱者與用戶集合中的每個 id 進行比較,並輸出匹配文檔的數量。
$project
投影輸出字段。
db.Channels.aggregate([
{ "$lookup": {
"from": "Users",
"let": { "subscribers": "$subscribers" },
"pipeline": [
{ "$match": { "$expr": { "$not": { "$in": [ "$_id", "$$subscribers" ] }}}},
{ "$count": "count" }
],
"as": "lookupresult"
}},
{ "$project": {
"channel": 1,
"unSubscribers": { "$arrayElemAt": [ "$lookupresult.count", 0 ] }
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.