简体   繁体   中英

Mongo DB - filter only future dates

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})
}

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

This should work:

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

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"} } }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM