Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
Convert JavaScript to mongoDB Aggregation

I am search how to convert this code in aggregation of MongoDB. let's suppose I have this service which will count the number of Games 'Fixtures' in each sports where start game will be soon I have two models Fixture which means the game and Sport which will be the sport, each Fixture have the sport Id that we can grouped during the aggregation. Here is a working example

export const countFixtures = async () => {
  const sports = await Sports.find();

  const countFixturesBySport = [];

  for (let index = 0; index < sports.length; index++) {
    const sport = sports[index];
    const countFixtures = await Fixture.countDocuments({
      Sport: sport._id,
      StartDate: { $gt: new Date() },
    });

    countFixturesBySport.push({
      sport: sport.Name,
      sportId: sport._id,
      fixturesCount: countFixtures,
    });
  }

  return countFixturesBySport;
};

I started with this code in mongoDB :

  await Sports.aggregate([
    {
      $lookup: {
        from: 'fixture',
        let: { fixture: '$fixture' },
        pipeline: [
          {
            $match: { $expr: { $eq: ['$_id', '$$fixture'] } },
          },{
            $project:
      {$addFields: {

sport:'Name',
sportId:'_id',
countFixture:''
}}

  ])
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here you go, you were on the right track using $lookup, just needed some minor tweaks in the actual logic.

db.sports.aggregate([
  {
    $lookup: {
      from: "fixture",
      let: {
        sportId: "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$Sport",
                "$$sportId"
              ]
            }
          }
        },
        {
          $project: {
            _id: 1
          }
        }
      ],
      as: "matchedFixtures"
    }
  },
  {
    $project: {
      _id: 0,
      sport: "$Name",
      sportId: "$_id",
      fixturesCount: {
        $size: "$matchedFixtures"
      }
    }
  }
])
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda