i am trying to fetch data from mongodb using aggregate query in nodejs for a specific date range,
let date = '20230925'
let year = date.slice(0, 4);
let month = String(date.slice(4, 6)).padStart(2, '0');
let day = date.slice(6, 8);
let startFormatedDate:any = `${year}-${month}-${day}T00:01:01.111+00:00`
let endFormatedDate:any = `${year}-${month}-${day}T23:58:58.998+00:00`
My aggregate query is
{ $sort: { updatedAt: -1 } },
{
$match: { $and: [
{ updatedAt: { $gt: startFormatedDate } },
{ updatedAt: { $lt: endFormatedDate } }
], },
},
with this condition i am getting data for 2023-09-25, but i am also getting data for 2023-09-26
can anyone suggest me what might be the issue
EDIT :
{
$match: { $and: [
{ updatedAt: { $gt: new Date(startFormatedDate) } },
{ updatedAt: { $lt: new Date(endFormatedDate) } },
],},
},
{ $sort: { updatedAt: -1 } },
with updated query, i am getting same result.
2
Answers
I would suggest a 3rd party Date library, e.g. Luxon. Then it would be simply:
To fetch data from MongoDB using an aggregate query in Node.js for a specific date range, you can use the $match operator in combination with $gte (greater than or equal) and $lte (less than or equal) operators. Example: