Mongo DB - filter only future dates

993 Views Asked by At

I'm making a request from Angular to a MongoDB table (accessed through RESTHeart) where each record contains a "startDate" field. When I fetch some records I get this date as an object:

startDate: {$date: 1609718400000}

I want to filter only future dates, however this filter query doesn't work as expected:

`{ "startDate": { $gt: { $date: ${Date.now()} } } }`

I'm still getting past dates. What am I doing wrong?

Edit: Here's my angular function:

getTerms(url: string): Observable<TermDto[]> {
    const params = createParams()
        .append('filter', `{ "startDate": { $gt: { $date: ${Date.now()} } } }`);
    
    return this.client.get<TermDto[]>(url, {params})
}
4

There are 4 best solutions below

0
On BEST ANSWER

The simplest way that worked for me was this:

{ startDate: { $gt: new Date() } }

My problem derived from using an aggregation - when I passed additional "avars" query parameter:

...?avars={'id': "some-id"}&filter={'startDate': {$gt: new Date()}}

It somehow ignored the "filter" parameter. It would be great if someone was able explain why it happens.

My final solution for aggregation was validating date on frontend.

3
On

MongoDb use ISO format, try replacing Date.now() with new Date().toISOString()

1
On

This should work:

{ startDate: { $gt: new Date(Date.now()) } }
0
On

RESTHeart uses the Extended JSON representation of MongoDB.

Dates are represented as {"$date": {"$numberLong": "<millis>"}}

Where < millis > is the epoch time in milliseconds.

So the correct filter is:

?filter={ "startDate": { "$gt": {"$date":  {"$numberLong": "1613381427"} } }