Home > Software design >  Find total of registered user in the last 7 days using mongoose
Find total of registered user in the last 7 days using mongoose

Time:04-09

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

CodePudding user response:

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.

CodePudding user response:

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",
    },
  },
]);

  • Related