MongoDB $ in con sottoquery
Aug 25 2020
Ho questo set di raccolta qui sotto ..
raccolta squadre:
{
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
},
]
}
raccolta capi:
{
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
},
]
}
La query dovrebbe essere simile a questa: SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')
Sono nuovo su mongodb e la mia domanda è come è possibile convertire la query sopra nel framework di aggregazione mongoDB?
Risposte
1 turivishal Aug 25 2020 at 14:27
Puoi usare $ lookup con pipeline,
$matchcontrolleràactivelo stato$lookupsi unirà alla raccolta dei leader$matchper controllareleader_ideorganization
$matchcontrollare i leader non è[]vuoto$projectper rimuovere illeaderscampo
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 } }
])
Terreno di gioco