Home > Mobile >  Add aggregation by the condition of the value of your own variable
Add aggregation by the condition of the value of your own variable

Time:10-07

I have two functions to get an array from monga using aggregation. The functions are completely the same, except for one pipeline - "match ({startTime: {$ gte: start}})". How can I leave one function and add a "math" only by the presence of the "start" variable, which is a date filter?

 let groupedByUserSessions
    if (lastDay) {
        const start = getDateFromString(lastDay);
        groupedByUserSessions = await getValuesByDate(start)
    } else {
        groupedByUserSessions = await getAllValues();
    }

The functions are completely the same,

function getValuesByDate(start) {
return Sessions.aggregate()
    .match({ startTime: { $gte: start } })
    .group({
        _id: { departament: "$departament", userAdName: "$userAdName" },
        cleanTime: { $sum: { $subtract: ["$commonTime", "$idlingTime"] } }
    })
    .group({
        _id: { departament: "$_id.departament"},
        users: { $push: {value: '$cleanTime', name: '$_id.userAdName'} },
        commonCleanTime: { $sum: "$cleanTime" }
    })
    .project({
        departament: '$_id.departament',
        users: '$users',
        commonCleanTime: '$commonCleanTime',
        performance: { $divide: [ "$commonCleanTime",  { $size: "$users" }] }
    });

}

CodePudding user response:

You can break the pipeline into a "head" and a "tail" and construct the head differently when the start argument is given:

function getValuesByDate(start) {
  let agg = Sessions.aggregate();

  if (start) {
    agg = agg.match({ startTime: { $gte: start } });
  }

  return agg
    .group({
      _id: { departament: '$departament', userAdName: '$userAdName' },
      cleanTime: { $sum: { $subtract: ['$commonTime', '$idlingTime'] } },
    })
    .group({
      _id: { departament: '$_id.departament' },
      users: { $push: { value: '$cleanTime', name: '$_id.userAdName' } },
      commonCleanTime: { $sum: '$cleanTime' },
    })
    .project({
      departament: '$_id.departament',
      users: '$users',
      commonCleanTime: '$commonCleanTime',
      performance: { $divide: ['$commonCleanTime', { $size: '$users' }] },
    });
}
  • Related