Filtering by date Field on aggregate

{
                    $lookup: {
                        from: "staffTimesheet",
                        localField: "_id",
                        foreignField: "missionId",
                        as: "matchingTimesheets"
                    }
                },
                {
                    $match: {
                        matchingTimesheets: {
                            $elemMatch: {
                                "schedule.startingDay": { $lte: date },
                                "schedule.endingDay": { $gte: date }
                            }
                        }
                    }
                }

Hi,

Here is two stage of my aggregate.
The “$lookup” works well and put “matchingTimesheets” (document’s array from my “Timesheet” collection) inside my current document.
But the $match never return anything.

If I try to do:

matchingTimesheets: {
            $elemMatch: {
                "schedule.overtime": true
            }
        }

Its working well and I get the correct documents with at least one document inside “matchingTimesheets” that have “schedule.overtime” equal to true.
So I think I just don’t understand how to work with date fields…

Edit:
const date = new Date().toJSON(); and it’s give me “2023-10-11T14:06:02.673Z”
In my database, startingDay and endingDay are formated like “2023-10-08T10:45:28.260+00:00”, maybe it’s part of the problem.

It is most likely the problem. To have comparable values field should have the same type. In your query, when you do

You assign a string value to the date varable. Which is most likely not comparable with native date in your database. Try with simply

const date = new Date() ;
1 Like