Danial Asraf Norbee
Danial Asraf Norbee

Reputation: 271

How to get the count of users within the last hour in MongoDB?

I'm trying to get the number of customers within the last hour but when I run the code, it returns an empty array (I have already checked that there are some data in updated within the last hour).

Here is the code.

const start = new Date();
start.setHours(0, 0, 0, 0); //milliseconds 00:00:00.000
const end = new Date();
end.setHours(23, 59, 59, 999); //milliseconds 23:59:59.999

const now = new Date().getTime();
const lastOneHr = new Date().getTime() - 60 * 60 * 1000;

//get chart info
router.post("/getcustomerchart/:adminId", (req, res, next) => {
  const adminId = req.params.adminId;
  Customer.aggregate([
    {
      $facet: {
        today: [
          {
            $match: {
              $and: [
                { adminId: adminId },
                { updated: { $gte: start, $lte: end } },
              ],
            },
          },
          { $count: "count" },
        ],
        lastHour: [
          {
            $match: {
              $and: [
                { adminId: adminId },
                { updated: { $gte: lastOneHr, $lte: now } },
              ],
            },
          },
          { $count: "count" },
        ],
        all: [{ $match: { adminId: adminId } }, { $count: "count" }],
      },
    },
  ])
    .then((docs) => {
      const response = {
        count: docs.length,
        customer_info: docs.map((doc) => {
          return {
            lastHour: doc.lastHour,
            today: doc.today,
            all: doc.all,
          };
        }),
      };
      res.status(200).json(response);
    })
    .catch((err) => {
      console.log(err);
      res.status(500).json({
        error: err,
      });
    });
});

Here's the result from Postman. I managed to get the count for today and all except for the lastHour. Is there something wrong with the format?

{
    "count": 1,
    "customer_info": [
        {
            "lastHour": [],
            "today": [
                {
                    "count": 1
                }
            ],
            "all": [
                {
                    "count": 10
                }
            ]
        }
    ]

Upvotes: 0

Views: 80

Answers (1)

thammada.ts
thammada.ts

Reputation: 5245

You have to convert your time to a Date object, MongoDB can not compare it with timestamp

So this will work

const now = new Date();
const lastOneHr = new Date(now.getTime() - 60 * 60 * 1000);

Upvotes: 1

Related Questions