Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

new Date() not match correctly data in mongodb

Hi,
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`,
          },
        },
      },      
    ]);

    res.status(200).json({
      status: 'success',
      data: {
        plan,
      },
    });
  } catch (err) {
    res.status(404).json({
      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`)
`${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