Search code examples
node.jsmongodbmongooseaggregate

aggregate query in mongoose mongodb nodejs


Hi I am trying the below query in my nodejs code

const totalCount = await model.countDocuments({
    'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
}).exec();

const activeCount = await model.countDocuments({
    'createdAt': { $gte: new Date(startDate), $lte: new Date(endDate) },
    'enabled': true,
}).exec();

const inactiveCount = (totalCount - activeCount);

return { totalCount, activeCount, inactiveCount };

Is there any way i can combine the above in a single query using aggregate in mongoose? Kindly guide me to the best solution .


Solution

  • Yes, quite simple using some basic operators, like so:

    model.aggregate([
      {
        $match: {
          createdAt: {
            $gte: new Date(startDate),
            $lte: new Date(endDate)
          }
        }
      },
      {
        $group: {
          _id: null,
          totalCount: {
            $sum: 1
          },
          activeCount: {
            $sum: {
              $cond: [
                {
                  $eq: [
                    "$enabled",
                    true
                  ]
                },
                1,
                0
              ]
            }
          }
        }
      },
      {
        $project: {
          _id: 0,
          totalCount: 1,
          activeCount: 1,
          inactiveCount: {
            $subtract: [
              "$totalCount",
              "$activeCount"
            ]
          }
        }
      }
    ])
    

    Mongo Playground