MongoDB $ in mit Unterabfrage
Aug 25 2020
Ich habe diese Sammlung unten ..
Teamsammlung:
{
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
},
]
}
Führer Sammlung:
{
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
},
]
}
Die Abfrage sollte folgendermaßen aussehen: SELECT * FROM teams WHERE active = 1 AND leader_id IN (SELECT id FROM leaders WHERE organization = 'Software Development')
Ich bin neu in Mongodb und meine Frage ist, wie die obige Abfrage in das MongoDB-Aggregationsframework konvertiert werden kann.
Antworten
1 turivishal Aug 25 2020 at 14:27
Sie können $ lookup mit Pipeline verwenden.
$matchwird denactiveStatus überprüfen$lookupwird der Leader-Sammlung beitreten$matchzu überprüfenleader_idundorganization
$matchScheckführer ist nicht[]leer$projectleadersFeld entfernen
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 } }
])
Spielplatz