我认为我需要在一个批处理中构建一个相当复杂的查询。
问题描述
用户可能会要求每天提供数据资源:
/api/data?startDate=2018-03-20&endDate=2018-02-24&mode=day
首先,后端将生成如下范围(我更喜欢使用伪代码):
rangesArray = [
{start: "2018-03-20 00:00:00", end: "2018-03-20 23:59:59"}
{start: "2018-03-21 00:00:00", end: "2018-03-21 23:59:59"}
{start: "2018-03-22 00:00:00", end: "2018-03-22 23:59:59"}
{start: "2018-03-23 00:00:00", end: "2018-03-23 23:59:59"}
{start: "2018-03-24 00:00:00", end: "2018-03-24 23:59:59"}
]
,查询如下所示:
for (var i = 0; i < rangesArray.length; i++) {
let query = {
'endDate': {'$gte': rangesArray[i].start},
'startDate': {'$lte': rangesArray[i].end}
}
// A huge no-no, as each request to remote DB takes some time
let dataForRange = await Data.find(query)
.limit(10) // Setting limit here, as we don't
// need to present all the data from each day.
// The limit is hardcoded for now but should
// be dependent on rangesArray.length
// Here, do something useful with dataForRange
}
我需要假设:
/api/data?startDate=2017-03-20&endDate=2018-04-20&mode=day
将无法执行)data = {startDate: „2018-03-22 13:20:00”, endDate: „2018-03-24 10:00:00”, temperature: 20.0}
,我应该只收到一次该特定记录。我认为这很难满足,所以这不是强制性要求。所以我期待这样的事情(巨大的伪代码):
complexQuery = [
{'$or': {endDate: {'$gte': '2018-03-20 00:00:00'}, 'startDate': {'$lte': „2018-03-20 23:59:59”}, 'limit': 10}},
{'$or’: {endDate: {'$gte': '2018-03-21 00:00:00'}, 'startDate': {'$lte': '2018-03-21 23:59:59'}, 'limit': 10}}
(...)
]
// One query to remote DB, hurray! But it doesn't work ...
let dataForRange = await Data.aggregate( complexQuery )