new Date() not match correctly data in mongodb

I’m learning MongoDb, and get a little issue.
I’m trying to match data like this

   $gte: new Date(`${year}-01-01`),
   $lte: new Date(`${year}-12-31`),

but it’s returning me an empty array

when I’m trying such variant, it match the data which I needed

 $gte: `${year}-01-01`,
 $lte: `${year}-12-31`,

why such approach $gte: new Date(${year}-01-01) not working correctly and not match data?

this is a full function where I 'm using it

exports.getMonthlyPlan = async (req, res) => {
  try {
    const year = req.params.year * 1; // 2021

    console.log(new Date(`${year}-01-01`));

    const plan = await Tour.aggregate([
        $unwind: '$startDates',
        $match: {
          startDates: {
            $gte: new Date(`${year}-01-01`),
            $lte: new Date(`${year}-12-31`),
            // $gte: `${year}-01-01`,
            // $lte: `${year}-12-31`,

      status: 'success',
      data: {
  } catch (err) {
      status: 'fail',
      message: err,

Hello Stanislavas,

In MongoDB queries, you compare data with same types. You don’t compare strings with objects and vice-versa.

new Date(`${year}-01-01`)

new Date is of type object (a Date object). The second value is of type string.

For example, consider these two documents in a collection:

{ "_id" : 1, "date" : "2020-05-30" }
{ "_id" : 2, "date" : ISODate("2020-05-30T00:00:00Z") }

And, these two queries:

db.test.find( { date: "2020-05-30" } )
db.test.find( { date: new Date("2020-05-30") } )

The first query returns the document with _id: 1. And, the second query returns the document with the _id: 2.

1 Like

$gte: ${year}-01-01,
$lte: ${year}-12-31,

problem solution:
$gte:"${new Date(${year}-01-01)}",
$lte:"${new Date(${year}-12-31)}"

Please read Formatting code and log snippets in posts and post your answer again. The way it is marked up it does not render correctly and readers are missing most of the important back ticks.

If I quote you, I think I get the original text which looks like:

Which I think is rendered the way you want, but I am not sure.