我从mongodb集合中获得了以下对象数组(超过500个对象):
var rentals = [{
deviceId: 1,
start_date: ISODate("2018-05-10T10:11:23.143Z") ,
end_date: ISODate("2018-07-11T12:19:53.143Z")
},{
deviceId: 2,
start_date: ISODate("2018-03-09T10:11:23.143Z") ,
end_date: ISODate("2018-03-10T12:19:53.143Z")
},{
deviceId: 2,
start_date: ISODate("2018-03-11T10:11:23.143Z") ,
end_date: ISODate("2018-05-12T12:19:53.143Z")
},{
deviceId: 3,
start_date: ISODate("2018-01-10T10:11:23.143Z") ,
end_date: ISODate("2018-09-11T12:19:53.143Z")
},{
...
}]
我在猫鼬中拥有以下阅读模式:
var readingSchema = new mongoose.Schema({
deviceId: Number,
timestamp: Date,
data: String
});
数据库中当前有10万个读数。
阅读文件示例:
[{
deviceId: 1,
timestamp: ISODate("2018-05-11T10:11:23.143Z"),
data: 'wathever'
},{
deviceId: 2,
timestamp: ISODate("2018-03-10T00:00:00.000Z"),
data: 'wathever'
},{
deviceId: 2,
timestamp: ISODate("2018-03-09T23:00:00.000Z"),
data: 'wathever'
},{
deviceId: 2,
timestamp: ISODate("2018-05-18T00:00:00.000Z"),
data: 'wathever'
},{
deviceId: 3,
timestamp: ISODate("2018-01-07T00:00:00.000Z"),
data: 'wathever'
},{
...
}]
我需要遍历Rentals数组,并为每个租借获取该设备在租借的起始日期和租借结束日期之间的读数。结果我需要一个读数数组。
我的解决方案是遍历租金数组,并查询覆盖率租金。
var allReadings = [];
Async.each(rentals, function(rental, callback) {
Reading.find({
timestamp: {
"$lte": new Date(rental.end_date)
},
timestamp: {
"$gte": new Date(rental.start_date)
},
"deviceId": { rental.deviceId }
},
function(err, readings) {
allReadings.push(readings);
callback();
});
}, function(err){
console.log(allReadings);
});
是否可以执行单个Mongoose查询并获得相同的结果,从而优化性能? 我想我需要使用聚合,但无法想到一种查询方式。
因此在示例数据中,结果应为:
[{
deviceId: 1,
timestamp: ISODate("2018-05-11T10:11:23.143Z"),
data: 'wathever'
},{
deviceId: 2,
timestamp: ISODate("2018-03-10T00:00:00.000Z"),
data: 'wathever'
},{
deviceId: 2,
timestamp: ISODate("2018-03-09T23:00:00.000Z"),
data: 'wathever'
}]
编辑:sql中的查询为:
SELECT rea.*
FROM ren
INNER JOIN readings rea
ON ren.devideId = rea.deviceId AND ren.start_date <= rea.fecha AND ren.end_date >= rea.timestamp