MongoDB/Mongoose querying at a specific date?

Viewed 278496

Is it possible to query for a specific date ?

I found in the mongo Cookbook that we can do it for a range Querying for a Date Range Like that :

db.posts.find({"created_on": {"$gte": start, "$lt": end}})

But is it possible for a specific date ? This doesn't work :

db.posts.find({"created_on": new Date(2012, 7, 14) })
10 Answers

i do it in this method and works fine

  public async getDatabaseorderbyDate(req: Request, res: Response) {
    const { dateQuery }: any = req.query
    const date = new Date(dateQuery)
    console.log(date)
    const today = date.toLocaleDateString(`fr-CA`).split('/').join('-')
    console.log(today)
    const creationDate = {
      "creationDate": {
        '$gte': `${today}T00:00:00.000Z`,
        '$lt': `${today}T23:59:59.999Z`
      }
    };

`
``

Problem I came into was filtering date in backend, when setting date to 0 hour, 0 minute, 0 second, 0 milisecond in node server it does in ISO time so current date 0 hour, 0 minute, 0 second, 0 milisecond of client may vary i.e. as a result which may gives a day after or before due to conversion of ISO time to local timezone

I fixed those by sending local time from client to server

 // If client is from Asia/Kathmandu timezone it will zero time in that zone.
// Note ISODate time with zero time is not equal to above mention
const timeFromClient = new Date(new Date().setHours(0,0,0,0)).getTime()

And used this time to filter the documents by using this query

const getDateQuery = (filterBy, time) => {
    const today = new Date(time);
    const tomorrow = new Date(today.getDate() + 1);

    switch(filterBy) {
        case 'past':
            return {
                $exists: true,
                $lt: today,
            };
        case 'present': 
            return {
                $exists: true,
                $gte: today,
                $lt: tomorrow
            };
        case 'future':
            return {
                $exists: true,
                $gte: tomorrow
            };
        default: 
            return {
                $exists: true
            };
    };
};
const users = await UserModel.find({
    expiryDate: getDateQuery('past', timeFromClient)
})

Seemed like none of the answers worked for me. Although someone mentioned a little hint, I managed to make it work with this code below.

let endDate = startingDate
endDate = endDate + 'T23:59:59';

Model.find({dateCreated: {$gte: startingDate, $lte: endDate}})

startingDate will be the specific date you want to query with.

I preferred this solution to avoid installing moment and just to pass the startingDate like "2021-04-01" in postman.

Well a very simple solution to this is given below

const start = new Date(2020-04-01);
start.setHours(0, 0, 0, 0);
const end = new Date(2021-04-01);
end.setHours(23, 59, 59, 999);
queryFilter.created_at={
    $gte:start,
    $lte:end
}
YourModel.find(queryFilter)

So, the above code simply finds the records from the given start date to the given end date.

Related