MongoDB $ in with subquery
Aug 25 2020
아래에이 컬렉션이 있습니다 ..
팀 컬렉션 :
{
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 집계 프레임 워크에서 어떻게 변환 할 수 있습니까?
답변
1 turivishal Aug 25 2020 at 14:27
파이프 라인과 함께 $ lookup 을 사용할 수 있습니다 .
$matchactive상태 를 확인 합니다$lookup리더 컬렉션에 합류합니다$match확인leader_id하고organization
$match리더가[]비어 있지 않습니다.$projectleaders필드 를 제거하려면
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 } }
])
운동장