Home > front end >  How to filter mongodb collection using date field?
How to filter mongodb collection using date field?

Time:10-07

I have date string like this

'2021-03-09'

And my mongodb collection like this

{
    "_id": {
        "$oid": "633aede250625c10dddfd57b"
    },
    "title": "test 1",
    "description": "Hello World",
    "date": {
        "$date": "2021-03-09T18:30:00.000Z"
    },
    "image": "fd16b297-9ad1-4e84-8c3e-715a33b351b3.png",
    "createdAt": {
        "$date": "2022-10-03T14:12:50.399Z"
    },
    "updatedAt": {
        "$date": "2022-10-03T14:12:50.399Z"
    },
    "__v": 0
},
{
    "_id": {
        "$oid": "633aede650625c10dddfd57f"
    },
    "title": "test 2",
    "description": "Hello World",
    "date": {
        "$date": "2022-03-09T18:30:00.000Z"
    },
    "image": "2084f157-6610-402d-9dca-6681fe6da7d4.png",
    "createdAt": {
        "$date": "2022-10-03T14:12:54.982Z"
    },
    "updatedAt": {
        "$date": "2022-10-03T14:12:54.982Z"
    },
    "__v": 0
}

I need filter and get the document by date field , and I tried follow the query like

return db.eventsCollection.find({
    date: date,
  }).catch((err: Error) => {
    logger.error(err);
    return null;
  });

But I couldn't get the results.

CodePudding user response:

Try to filter using a range of dates (today and tomorrow);

const today = new Date(date);
const tomorrow = new Date(date);
tomorrow.setDate(tomorrow.getDate()   1);

return db.eventsCollection.find({
    date: { $gte: today , $lt: tomorrow }
  }).catch((err: Error) => {
    logger.error(err);
    return null;
  });

CodePudding user response:

As you are given a date string as input, it would be more sensible to use $dateToString to convert your date into a date string for comparison.

db.collection.find({
  $expr: {
    $eq: [
      {
        "$dateToString": {
          "date": "$date",
          "format": "%Y-%m-%d"
        }
      },
      // your input here
      "2021-03-09"
    ]
  }
})

Here is the Mongo Playground for your reference.

  • Related