gpt4 book ai didi

带有子查询的 MongoDB $in

转载 作者:行者123 更新时间:2023-12-05 03:50:11 25 4
gpt4 key购买 nike

我下面有这组合集..

团队集合:

{
total: 3
data: [
{
"_id": "t1",
"name": "white horse",
"leader_id": "L1"
"teamScore": 12,
"active": 1
},
{
"_id": "t2",
"name": "green hornets",
"leader_id": "L2",
"teamScore": 9,
"active": 1
},
{
"_id": "t3",
"name": "pink flaminggo",
"leader_id": "L3",
"teamScore": 22,
"active": 1
},
]
}

领袖合集:

{
total: 3
data: [
{
"_id": "L1",
"name": "John Doe",
"organization": "Software Development",
"active": 1
},
{
"_id": "L2",
"name": "Peter Piper",
"organization": "Software Development"
"active": 1
},
{
"_id": "L3",
"name": "Mary Lamb",
"organization": "Accounting Department"
"active": 1
},
]
}

查询应如下所示:SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')

我是 mongodb 的新手,我的问题是如何在 mongoDB 聚合框架中转换上面的查询?

最佳答案

您可以使用 $lookup带管道,

  • $match 将检查 active 状态
  • $lookup 将加入 leaders 集合
    • $match 检查 leader_idorganization
  • $match 检查领导者是否[] 为空
  • $project 删除 leaders 字段
db.teams.aggregate([
{ $match: { active: 1 } },
{
$lookup: {
from: "leaders",
let: { leader_id: "$leader_id" },
as: "leaders",
pipeline: [
{
$match: {
$and: [
{ $expr: { $eq: ["$_id", "$$leader_id"] } },
{ organization: "Software Development" }
]
}
}
]
}
},
{ $match: { leaders: { $ne: [] } } },
{ $project: { leaders: 0 } }
])

Playground

关于带有子查询的 MongoDB $in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63573853/

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