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