'Find total of registered user in the last 7 days using mongoose

I'm storing my data in a schema like this

enter image description here

I wonder how i can create a query in mongoose to get count of created user in the last 7 days where I expect my output to be like this

{ day1: 4, day2: 4, day3: 9, day4: 12, day5: 7, day6: 0, day7: 10 }

sorry for my bad english



Solution 1:[1]

Hello I used mongo aggregate to group the data you need daily like this:

const toDate = new Date("2022-04-08");

const fromDate = new Date("2022-04-01");

const data = await User.aggregate([{
    $match: {
      createdAt: {
        $gte: new Date(fromDate),
        $lte: new Date(toDate),
      },
    },
  },
  {
    $sort: {
      createdAt: -1
    }
  },
  {
    $project: {
      day: {
        $dayOfMonth: "$createdAt"
      },
      month: {
        $month: "$createdAt"
      },
      year: {
        $year: "$createdAt"
      },
    },
  },
  {
    $group: {
      _id: {
        day: "$day",
        year: "$year",
        month: "$month",
      },
      count: {
        $sum: 1
      },
    },
  },
  {
    $project: {
      _id: 0,
      day: "$_id.day",
      month: "$_id.month",
      year: "$_id.year",
      count: "$count",
    },
  },
]);

Solution 2:[2]

const usersCount = await User.countDocuments({
  created_at: { $lt: new Date('2022-04-08'), $gt: new Date('2022-04-01') }
});

This will give you count for users created in last seven days. Dynamic date you can generate in your express backend.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xanik
Solution 2 Nishant Chorge