简体   繁体   中英

Add value from another collection in MongoDB

I fetch data from an external API which give me two collections. One for football games and one for football competitions. I save this data in MongoDB. When I query a football game I want to know each teams standing in the competition.

These are the models.

Game

{
    ...,
    homeTeam: {
        id: 1234
    },
    awayTeam: {
        id: 2345
    },
    ...
}

Competition

{
    ...
    standings: [
    {
        position: 1,
        team: {
            id: 1234,
            ...
        },
        ...
    },
    {
        position: 2,
        team: {
            id: 2345,
            ...
        },
        ...
    }
    ]
}

I've tried using aggregation with $lookup but I can't get it to work the way I want.

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',
        }}
    ]);

What I want to have as a result for each game is this.

{
    ...,
    homeTeam: {
        id: 1234,
        position: 1
    },
    awayTeam: {
        id: 2345
        position: 2
    },
    ...
}

This can be easily done like this with the help of forEach and an if statement. Everything is explained in the comments. Also, feel free to ask if you have any doubts with the code.

let objectsArr = Object.keys(firstOBJ); // get properties
let answer = []; // a new array for your answer
let childs = Object.keys(secondOBJ); // get the properties of secondOBJ
secondOBJ[childs].forEach((val, i) => { // for every property in secondOBJ
  if (firstOBJ[objectsArr[i]].id == val.team.id) { // we match the id's if they are same then we proceed
    name = objectsArr[i]; // we get the name
    answer.push({ // and we pust with the name
      [name]: {
        id: val.team.id, // along with the corresponding properties
        position: val.position
      }
    })
  }
});

Test snippet for the code above.

 let firstOBJ = { homeTeam: { id: 1234 }, awayTeam: { id: 2345 } } let secondOBJ = { standings: [{ position: 1, team: { id: 1234, }, }, { position: 2, team: { id: 2345 }, } ] } let objectsArr = Object.keys(firstOBJ); let answer = []; secondOBJ[Object.keys(secondOBJ)].forEach((val, i) => { if (firstOBJ[objectsArr[i]].id == val.team.id) answer.push({ [objectsArr[i]]: { id: val.team.id, position: val.position } }); }); console.log(answer) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM