Waterfall
Waterfall

Reputation: 704

How do you count records for the current month?

Using mongo or mongoose, how would I get the total number of records for the current month?

I have this but it is giving me a total for every month, I just want a count of records for the current month.

  const genTotal = await General.aggregate([
    {
      $group: {
        _id: {
          year: { $year: "$visitDate" },
          month: { $month: "$visitDate" },
        },
        Total: { $sum: 1 },
      },
    },
  ]);

I also tried this:

  const genTotal = await General.aggregate([
    {
      $group: {
        _id: {
          month: { $month: "$visitDate" },
        },
        Total: { $sum: 1 },
      },
    },
    {
      $match: { $month: 3 },
    },
  ]);

Upvotes: 0

Views: 749

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Add a match stage in the beginning to filter out the past month's documents try this:

let month = new Date().getMonth();

const genTotal = await General.aggregate([
    {
        $match: {
            $expr: {
                $eq: [{ $month: "$visitDate" }, month]
            }
        }
    },
    {
        $group: {
            _id: {
                year: { $year: "$visitDate" },
                month: { $month: "$visitDate" },
            },
            Total: { $sum: 1 }
        }
    }
]);

Upvotes: 1

Related Questions