在$ lookup

时间:2019-06-13 16:19:37

标签: mongodb mongodb-query aggregation-framework

我在devicesevents之间存在一对多的关系。我正在尝试查询devices,同时将其所有events都加入其中,这也必须匹配另一个条件。

以下是每个表的相关属性:

设备:

{
  networkId: String,
  serial: String // Unique device ID.
  ...
}

事件:

{
  deviceSerial: String, // The "serial" field of the device this event is for.
  ts: Number // Unix epoch timestamp in seconds.
  ...
}

我发现$lookup的3.6语法完全可以实现我想要的功能,但是它似乎没有用。我得到了正确的设备,但是events数组始终返回为空,但是对于某些事实,我知道存在符合条件的事件。

我的管道:

[
  {
    $match: {
      networkId: 'N_660903245316632251'
    }
  },
  {
    $lookup: {
      from: 'events',
      let: {'deviceSerial': '$deviceSerial'},
      pipeline: [
        $match: {
          deviceSerial: '$$deviceSerial',
          ts: {$gte: 1556686800, $lte: 1559365199}
        }
      ]
    }
  }
]

所选设备成功返回结果,但事件数组始终为空:

[
  {
    ...
    events: []
  }
  ...
]

1 个答案:

答案 0 :(得分:1)

这里缺少的一件事是,您需要使用表达式($expr)来引用let语句定义的变量:

{
    $lookup: {
        from: 'events',
        let: {'deviceSerial': '$deviceSerial'},
        pipeline: [
            $match: {
                {
                    $expr: {
                        $and: [
                            { $eq: [ "$deviceSerial", "$$deviceSerial" ] },
                            { $gte: [ "$ts", 1556686800 ] },
                            { $lte: [ "$ts", 1559365199] }
                        ]
                    }
                }
            }
        ] 
    }
}
相关问题