Home > Mobile >  Convert JavaScript to mongoDB Aggregation
Convert JavaScript to mongoDB Aggregation

Time:12-21

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:''
}}

  ])

CodePudding user response:

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"
      }
    }
  }
])
  • Related