Home > Back-end >  Mongoose filter by Month only
Mongoose filter by Month only

Time:08-07

I've tried filtering dates in mongoose by using $gte and $lt.

My problem is that I want to get all the data in January or February. Any ideas on how to do it? Thanks in advance.

here is my sample json data

[
   "date": {
        "createdAt": "2022-08-06T09:40:14.865Z"
   },
  "date": {
        "createdAt": "2022-08-05T09:40:14.865Z"
   },
]

CodePudding user response:

To fetch data based between two dates for example from January 1st to last day of February you can do something like:

db.collection.find({
    day: {
        $gt: ISODate("2022-01-01"),
        $lt: ISODate("2022-03-01")
    }
})

CodePudding user response:

More native, and faster solution that does not require providing 'year' into the date, is by using $month operator https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/month/?_ga=2.58659434.1978243809.1659820987-451560266.1650302835

 db.collection.find({ "$expr": { "$eq": [{ "$month": "$createdAt" }, 1] }})

or if you want to ask for two months at once

 db.collection.find({ "$expr": { "$in": [{ "$month": "$_created_at" }, [1,2]] }})
  • Related