Mongodb 数组中所有对象的单个mongoose查询
我从mongodb集合中获得了以下对象数组(超过500个对象):Mongodb 数组中所有对象的单个mongoose查询,mongodb,mongoose,Mongodb,Mongoose,我从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") ,
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")
},{
...
}]
我在Mongoose中获得了以下阅读资料:
var readingSchema = new mongoose.Schema({
deviceId: Number,
timestamp: Date,
data: String
});
目前,以DB为单位的读数为100k
阅读资料文件示例:
[{
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数组,并为每次租赁获取在租赁开始日期和租赁结束日期之间生成的设备读数。我需要一个读数数组作为结果
我的解决方案是迭代rentals数组并查询reach rental
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
选择rea*
任
内部连接读数rea
在ren.deviceId=rea.deviceId和ren.start\u date=rea.timestamp上
可能的重复。使用$filter
@Veeram我不确定您的链接是否有用。如何一次查找数组中的所有租金?使用$filter一次查找一个数组值,并输出与查询条件匹配的数组元素。那么上面文档的输出应该是什么?@AnthonyWinzlet输出应该是读数数组