gpt4 book ai didi

javascript - 使用 $lookup 在 mongodb 中进行外部连接

转载 作者:可可西里 更新时间:2023-11-01 10:38:22 26 4
gpt4 key购买 nike

我有一个 channel 收藏

{
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"
}

现在我需要找到 channel 名称“Xamper”并计算不在subscribers数组中的用户

所以输出将是

{
channel: "Xamper",
unSubscribers: 1
}

类似于SQL的outer excluding join

enter image description here

最佳答案

您可以在 3.6 中使用以下管道。

$lookup使用管道将 Channels 集合加入订阅者的 Users 集合

$count$not $in将订阅者与 Users 集合中的每个 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 ] }
}}
])

关于javascript - 使用 $lookup 在 mongodb 中进行外部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com