因此,我想进行查询以查找集合中存在的所有任务,并以在两个给定日期之间具有date属性为条件。
我使用了Between关键字,但是它没有在结果中包括参数的值。
例如,如果参数为2019-09-20和2019-09-25,则计划在相同日期进行的任务不会在响应中返回。
我尝试使用LessThanEqual和GreaterThanEqual,但出现以下错误:
org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'task.date' expression specified as 'task.date : Document{{$lte=Thu Sep 26 00:00:00 CEST 2019}}'. Criteria already contains 'task.date : Document{{$gte=Wed Sep 25 00:00:00 CEST 2019}}'.
这就是为什么我想知道是否有一种方法可以在同一字段上查询两次。
这是我的存储库。
public interface TaskRepository extends MongoRepository<TaskEntry, String> {
List<TaskEntry> findByTask_DateGreaterThanEqualAndTask_DateLessThanEqual(Date dateFrom, Date dateTo);
}
谢谢。
更新:
这是我使用rustyx的答案后的收集,查询和结果的说明性示例。
这些是我的文档:
[
{
"id": "5c3da5b163c2789768d1402a",
"code": "0000001",
"createdDate": "2019-01-15T09:19:45.114+0000",
"lastModifiedDate": "2019-01-15T09:19:45.114+0000",
"task": {
"codeRule": null,
"title": "Task 1",
"date": "2019-09-26T00:00:00.000+0000",
"description": "This is the first task",
"type": "UNITARY",
"result": null
}
},
{
"id": "5c3da7dc63c2789768d1402b",
"code": "0000002",
"createdDate": "2019-01-15T09:29:00.125+0000",
"lastModifiedDate": "2019-01-15T09:29:00.125+0000",
"task": {
"codeRule": null,
"title": "Task 2",
"date": "2019-09-26T00:00:00.000+0000",
"description": "This is the second task",
"type": "UNITARY",
"result": null
}
},
{
"id": "5c3db0c763c27868b41e022b",
"code": "0000003",
"createdDate": "2019-01-15T10:07:03.693+0000",
"lastModifiedDate": "2019-01-15T10:07:03.693+0000",
"task": {
"codeRule": null,
"title": "Task 3",
"date": "2019-09-28T00:00:00.000+0000",
"description": "This is the third task",
"type": "UNITARY",
"result": null
}
}
]
这是我通过以下方法得到的响应:
@Query("{'task.date': {$gte: ?0, $lte:?1 }}")
List<TaskEntry> findByTask_DateBetween(Date dateFrom, Date dateTo);
这:
/tasks?dateFrom=2019-09-26&dateTo=2019-09-28
响应:
[
{
"id": "5c3da5b163c2789768d1402a",
"code": "0000001",
"createdDate": "2019-01-15T09:19:45.114+0000",
"lastModifiedDate": "2019-01-15T09:19:45.114+0000",
"task": {
"codeRule": null,
"title": "Task 1",
"date": "2019-09-26T00:00:00.000+0000",
"description": "This is the first task",
"type": "UNITARY",
"result": null
}
},
{
"id": "5c3da7dc63c2789768d1402b",
"code": "0000002",
"createdDate": "2019-01-15T09:29:00.125+0000",
"lastModifiedDate": "2019-01-15T09:29:00.125+0000",
"task": {
"codeRule": null,
"title": "Task 2",
"date": "2019-09-26T00:00:00.000+0000",
"description": "This is the second task",
"type": "UNITARY",
"result": null
}
}
]
日期为2019-09-26的任务已添加到响应中,这意味着 $ gte:?0 正在运行,但日期为2019-09-28的任务不在其中。
>答案 0 :(得分:1)
您可以使用“之间”:
List<TaskEntry> findByTask_DateBetween(Date dateFrom, Date dateTo);
如果这还不够,请使用自定义查询:
@Query("{'date': {$gte: ?0, $lte:?1 }}")
List<TaskEntry> findByTask_DateBetween(Date dateFrom, Date dateTo);