Home > Software design >  find mongodb collection document with date String
find mongodb collection document with date String

Time:05-18

I have date string like

2022-05-17

And My mongodb collection document like

{
  "_id": { "$oid": "aabbccddeeff" },
  "title": "test",
  "content": "test",
  "author": "tester",
  "churchId": { "$oid": "e5eakjshuwb3546" },
  "markAsRead": false,
  "createdAt": { "$date": "2022-05-17T08:18:57.174Z" },
  "updatedAt": { "$date": "2022-05-17T08:18:57.174Z" },
  "__v": 0
}

Now How do I find this collection using date string like mention above.

I have used this query as well

.find({ churchId, createdAt: new Date(createdAt) }, ' -__v')

But couldn't work.

CodePudding user response:

You can do something like

createdAt: {$gte: ISODate("2022-05-17T00:00:00"), $lte: ISODate("2022-05-17T23:59:59")}

It will bring all the docs falls on the given day.

CodePudding user response:

If project environment like typescript ,then ISODate shows an error like:

'cannot find ISODate'

So we can use new Date() class like:

createdAt: {
  $gte: new Date("2022-05-17T00:00:00"),
  $lte: new Date("2022-05-17T23:59:59")
}
  • Related