I want to filter data by year in MongoDB. If I pass year 2022 then show only 2022 year data and when I pass 2023 show 2023 data only. I am not getting how to filter. I use $gte
and $lte
tag but it return empty. Also let me know who I will filter by specific year and month. Let say year 2023 and month 11.
Data –
{
_id: new ObjectId("63ac23187dc7d"),
details: 'hii there i am feeling great today',
status: '1',
createdAt: 2021-11-28T11:06:00.736Z
},
{
_id: new ObjectId("63ac23b357dc96"),
details: 'hi i am feeling good today',
status: '1',
createdAt: 2022-12-28T11:08:40.400Z,
},
{
_id: new ObjectId("63b2b2afa0d8e"),
details: 'Hello!! This is Ankit and feeling good',
status: '1',
createdAt: 2022-11-14T10:31:36.098Z
},
{
_id: new ObjectId("63b2b2sswa0d91"),
details: 'Felling bad a bit',
status: '1',
createdAt: 2023-01-02T10:32:27.149Z
},
{
_id: new ObjectId("63b2b2a0d94"),
details: 'Hmm, its ok ok',
status: '1',
createdAt: 2023-01-02T10:33:19.386Z
}
2
Answers
If you are looking after a generic approach to filter specific years and months which are not necessarily consecutive, one option is:
See how it works on the playground example
Assuming
createdaAt
is what you want to filter by, and that it is a true date. For a single year you’d write a query like this:For a single month, it’s: