我下面有这组合集..
团队集合:
{
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_id
和organization
$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 } }
])
关于带有子查询的 MongoDB $in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63573853/