javascriptmongodbmongooseecmascript-6

How to count documents created within specific month or year using createdAt field in mongoDB?


I'm building an admin dashboard and i want to count users created in given month or year. I'm using the countDocuments() method with the query param "createdAt" but the result is 0 and i'm expecting a result of 2.

Here is the code:

const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();

const newClientThisMonth = await User.countDocuments({
    createdAt: { $eq: currentYear },
});

The "newClientThisYear" variable is returning 0 instead of 2. I know i'm using the countDocuments() method in the wrong way with this field but with other fields like the "role" field everything is working fine.

const clientUsersCount = await User.countDocuments({ role: "user" });

So, how will you do it if it was you ?


Solution

  • Your current code looks to me that it is comparing a date to simply a year/month, like 2024 or 10. I don't think it is expected to return any data.

    One of the canonical ways to do this in MongoDB would be comparing the year and month together(and only year and month) with $year and $month operators.

    db.collection.aggregate([
      {
        "$match": {
          "$expr": {
            "$let": {
              "vars": {
                // your input here
                "yearInput": 2024,
                "monthInput": 10
              },
              "in": {
                "$and": [
                  {
                    "$eq": [
                      "$$yearInput",
                      {
                        "$year": "$createdAt"
                      }
                    ]
                  },
                  {
                    "$eq": [
                      "$$monthInput",
                      {
                        "$month": "$createdAt"
                      }
                    ]
                  }
                ]
              }
            }
          }
        }
      },
      {
        "$count": "count"
      }
    ])
    

    Mongo Playground