Extracting information from an external API provides me with two separate data sets: one for football matches and another for football competitions. I store this information in MongoDB. Inquiring about a specific football match, I am interested in knowing the standings of each team within the associated competition.
Below are the models being used:
Game
{
...,
homeTeam: {
id: 1234
},
awayTeam: {
id: 2345
},
...
}
Competition
{
...
standings: [
{
position: 1,
team: {
id: 1234,
...
},
...
},
{
position: 2,
team: {
id: 2345,
...
},
...
}
]
}
I attempted using aggregation with $lookup but encountered challenges getting it to perform as desired.
const game = await Game.aggregate([
{$match: {'competition.id': parseInt(req.params.id)} },
{$lookup: {
from: 'competitions',
localField: 'homeTeam.id',
foreignField: 'standings.team.id',
as: 'homeTeam.position',
}}
]);
The expected outcome for each game is represented below:
{
...,
homeTeam: {
id: 1234,
position: 1
},
awayTeam: {
id: 2345
position: 2
},
...
}