'Select documents in collection that match foreign key value
I want to use MongoDB aggregate to grab some documents in collection Events that reference the collection Program with the constraint of Program.type
Events
{
_id: ObjectId,
programId: ObjectId
}
Programs
{
_id: ObjectId,
type: "Type A"
}
The pseudo sql-like query would be like select * from events where event.id = 1234 and where program.type = "Type A"
I've got this and I have no idea what I'm doing.
const pipeline = [
{
$match: {_id: id}
},
{
$lookup: {
from: 'programs',
localField: '_id',
foreignField: 'programId',
as: 'program'
}
},
{
$unwind: '$program'
},
{
$match: {'program.type': 'Type A'}
}
]
I actually thought this worked but it failed when I tried different types.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
