Search code examples
node.jsmongodbmongoosenosqlmern

Mongoose return documents created before a particular month


I am trying to get users who registered before a particular month:

const getUsersWhoRegisteredBeforeAGivenMonth = async (month, year) => {
  const project_stage = {
    $project: {
      year: { $year: "$date" },
      month: { $month: "$date" },
    },
  };

  const filter_stage = {
    $match: {
      year: {
        $lte: parseInt(year),
      },
      month: {
        $lte: parseInt(month),
      },
    },
  };

  const pipeline = [project_stage, filter_stage];
  const users = await User.aggregate(pipeline);
  return users;
};

But, this returns the wrong results.
When month = 1 and year = 2022, instead of returning all the documents created before 01/2022, it returns the documents created from the beginning of 2022 until the end of 01/2022 and the documents created from the beginning of 2021 until the end of 01/2021.
And if I pick 02/2022, it will do the same thing until the end of 02/2022 and 01/2021.

Any idea how to fix this?


Solution

  • Would suggest using $dateFromParts to compare date for your scenario.

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $lt: [
              "$date",
              {
                "$dateFromParts": {
                  "year": 2022,
                  "month": 2
                }
              }
            ]
          }
        }
      }
    ])
    

    Sample Mongo Playground