[英]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.我正在从 Angular 向 MongoDB 表(通过 RESTHeart 访问)发出请求,其中每条记录都包含一个“startDate”字段。 When I fetch some records I get this date as an object:
当我获取一些记录时,我得到这个日期为 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:编辑:这是我的 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()
MongoDb 使用 ISO 格式,尝试用
new Date().toISOString()
替换Date.now()
)
This should work:这应该有效:
{ startDate: { $gt: new Date(Date.now()) } }
RESTHeart uses the Extended JSON representation of MongoDB. RESTHeart 使用 MongoDB 的扩展 JSON表示。
Dates are represented as {"$date": {"$numberLong": "<millis>"}}
日期表示为
{"$date": {"$numberLong": "<millis>"}}
Where < millis >
is the epoch time in milliseconds.其中
< millis >
是以毫秒为单位的纪元时间。
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”查询参数时:
...?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.我最终的聚合解决方案是在前端验证日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.