2

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

  ])
2
  • 2
    Would be helpful if you can provide sample dataset and the corresponding expected output Commented Dec 20, 2021 at 14:56
  • totally, I created to files in github repo : github.com/anasbenyaiche/data-set-example/tree/main Commented Dec 20, 2021 at 15:10

1 Answer 1

1

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"
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much , thanks for explaining me the error @Tom Slabbaert

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.