Al Imran Hossain
Al Imran Hossain

Reputation: 205

Mongoose: How many users were created for every day

I need to count how many users were created every day last week. I can get a total created user number of last week

    var d = new Date();
    d.setDate(d.getDate() - 7);

    const data = await User.count({ "createdAt": { $gt: d } })
    return res.status(200).json({ error: false, data: data })

sample data:

{
    "_id": "612fa439gdb04331d6ea1e5d",
    "name": "imran",
    "createdAt": "2021-09-01T16:03:05.266Z",
},
 {
    "_id": "612fa439ddb44331d6ea1e5d",
    "name": "Hossain",
    "createdAt": "2021-08-31T16:03:05.266Z",
},
...........

expected output :

"user_count" : {
    02-09-2021: 3,
    01-09-2021: 5,
    31-08-2021: 3,
    30-08-2021: 5,
    ...
 }

Use this API, I want to create a chart to show statistics. that API should provide which day, how many users were created. How can I do that?

Upvotes: 2

Views: 557

Answers (2)

eol
eol

Reputation: 24565

If you want to do this through mongodb, you can try converting your createdAt field to an actual date and then group by this date after formatting it to yyyy-mm-dd. Something like this:

db.collection.aggregate([
  {
    $addFields: {
      createdAtDate: {
        $toDate: "$createdAt"
      },
      
    }
  },
  {
    $group: {
      _id: {
        $dateToString: {
          format: "%Y-%m-%d",
          date: "$createdAtDate"
        }
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      count: 1,
      date: "$_id",
      _id: 0
    }
  }
])

Here's an example on mongoplayground: https://mongoplayground.net/p/8D9-kHZmPTo

Upvotes: 2

Harshit Rastogi
Harshit Rastogi

Reputation: 2122

I guess you should create a new object like this:

var d = new Date();
d.setDate(d.getDate() - 7);

const data = await User.find({ "createdAt": { $gt: d } })
var userData = {};

data.forEach((user) => {
    const createdAt = user.createdAt.split("T")[0];
    const count = userData[createdAt] ? userData[createdAt] : 0;
    userData[createdAt] = count + 1;
})

console.log(userData)

Upvotes: 0

Related Questions