我的租赁模式:
var rentals = [{
deviceId: 1,
start_date: ISODate("2018-05-10T10:11:23.143Z") ,
end_date: ISODate("2018-07-11T12:19:53.143Z")
},{
...
}]
我的阅读模式:
[{
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-05-18T00:00:00.000Z"),
data: 'wathever'
},{
...
}]
我需要使用$lookup将这两个集合与读数结合起来,但是对于每个租用(deviceId),我只需要获得一个读数,即时间戳更高的读数(最新)。数据库中的每个租金都有N个读数。
我的方法:
Rental.aggregate([
{ "$match": {
clientId : ObjectId(req.params.clientId)
}},
{
$lookup:{
from:"readings",
localField:"deviceId",
foreignField:"deviceId",
let: { timestamp: "$timestamp"},
pipeline: [
{ $sort: { "$$timestamp": -1}},
{ $limit : 1 },
],
as:"lastReading"
}
},
{ $unwind: "$lastReading" },
], function(err, result) {
console.log(result);
});
我发现一个错误:
(node:1392) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: arguments to $l
ookup must be strings, let: { time: "$time" } is type object
读取模式中的时间字段是日期类型。
一定是我做的不对。。。