MongoDB 根据日期使用查找和管道将集合与其自身连接:连接结果集中没有结果

MongoDB joining collection to itself with lookup and pipeline, based on date: no results in joined result set

我正在尝试将集合与其自身连接,以便在一个查询中我可以接收文档和紧接在它之前的文档。我正在尝试使用 aggregate 和 `$lookup' 来做到这一点。

这是一些示例数据:

[
  {
    "_id": {
      "$oid": "61e40955cb65f4a8edec3461"
    },
    "ImageName": "2022-01-16-120228.png",
    "Start": {
      "$date": "2022-01-16T12:02:29.437Z"
    }
  },
  {
    "_id": {
      "$oid": "61e40957cb65f4a8edec3463"
    },
    "ImageName": "2022-01-16-120230.png",
    "Start": {
      "$date": "2022-01-16T12:02:31.443Z"
    }
  },
  {
    "_id": {
      "$oid": "61e4095acb65f4a8edec3469"
    },
    "ImageName": "2022-01-16-120233.png",
    "Start": {
      "$date": "2022-01-16T12:02:33.189Z"
    }
  },
  {
    "_id": {
      "$oid": "61e4095ccb65f4a8edec346b"
    },
    "ImageName": "2022-01-16-120235.png",
    "Start": {
      "$date": "2022-01-16T12:02:35.288Z"
    }
  }]

对于此集合中的每个文档,我想在 Start 日期之前带回紧接其之前的文档,如下所示:

db.Captures.aggregate([{
  $lookup: {
    from: 'Captures',
    as: 'precedingCaptures',
    let: {
      'start': '$Start'
    },
    pipeline: [
      {
        $sort: {
          'Start': -1
        }
      },
      { $match: {
        'Start': {$lt: '$$start'}
      }},
      { '$limit': 1 }
    ]
  }
}])

但是在我生成的文档中 precedingCaptures 是空的。我做错了什么?

您不能将 $match 的“简单”形式与 pipeline $lookup 一起使用。您必须使用此处注明的 $expr 形式:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

这会起作用:

db.foo.aggregate([
    {$lookup: {
        from: 'foo',
        as: 'precedingCaptures',
        let: { 'start': '$Start'},
        pipeline: [
            { $match: {$expr: {$lt:['$Start','$$start']} }},  // $expr form
            { $sort: {'Start': -1}},
            { $limit: 1 }
        ]
    }}
]);