Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!