代码之家  ›  专栏  ›  技术社区  ›  Egidi

在Moongose中排序后,将$lookup results限制为1个文档

  •  0
  • Egidi  · 技术社区  · 7 年前

    我的租赁模式:

    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
    

    读取模式中的时间字段是日期类型。 一定是我做的不对。。。

    1 回复  |  直到 7 年前
        1
  •  1
  •   s7vr    7 年前

    您可以使用下面的聚合来对连接的数据进行后期处理。

    $lookup 根据设备id获取所有读数 $unwind / $sort 按时间戳对读数进行排序。

    $group 从每间出租房收集最后的读数。

    有点像

    Rental.aggregate([
      {"$match":{"clientId":ObjectId(req.params.clientId)}},
      {"$lookup":{
        "from":"readings",
        "localField":"deviceId",
        "foreignField":"deviceId",
        "as":"readings"
      }},
      {"$unwind":"$readings"},
      {"$sort":{"readings.timestamp":-1}},
      {"$group":{"_id":"$_id","lastReading":{"$first":"$readings"}}}
    ])