MongoDB聚合-加入($ lookup)具有最高价值的单个文档

时间:2018-10-04 12:12:09

标签: mongodb aggregation-framework

我正在使用$ lookup运行一些聚合命令,并希望基于某个值从查找结果中仅选择一个文档。

示例:

// Add some users
db.users.insert([
  {_id: "1", name: "john"},
  {_id: "2", name: "jack"},
  {_id: "3", name: "jenny"}
])

// Users have projects (owner field refers to user _id)
db.projects.insert([
  // Johns projects
  {owner: "1", name: "john1", lastUpdate: ISODate("2018-01-01T11:00:00")},
  {owner: "1", name: "john2", lastUpdate: ISODate("2018-01-01T12:00:00")},
  // Jennys projects
  {owner: "3", name: "jenny1", lastUpdate: ISODate("2018-01-01T11:00:00")},
  {owner: "3", name: "jenny2", lastUpdate: ISODate("2018-01-01T13:00:00")},
  {owner: "3", name: "jenny3", lastUpdate: ISODate("2018-01-01T12:00:00")}
])

现在,我想在users上进行一些汇总,并添加具有最新lastUpdate值的项目。 我找到了两种实现方法,想知道如何才能更好地做到(性能方面),以及是否有第三种更简单和/或更有效。

(注意:聚合查询的目的不仅仅是获取最新的项目,它只是更复杂查询中的一步) (注2:MongoDB 3.6)

谢谢!

第一个选项

db.users.aggregate([
  {$lookup: {from: 'projects', localField: '_id', foreignField: 'owner', as: 'projects'}},
  {$addFields: {
    latest_project: {
      $arrayElemAt: [
        {
          $filter: {
            input: '$projects',
            as: 'proj',
            cond: { $eq: [ '$$proj.lastUpdate', { $max: '$projects.lastUpdate' } ] }
          }
        }, 0
      ]
    }
  }}
])

第二个选项

db.users.aggregate([
  {$lookup: {
    from: 'projects',
    let: {uid: '$_id'},
    pipeline: [
      {$match: {$expr: {$eq: [ "$owner", "$$uid" ]}}},
      {$sort: {lastUpdate: -1}},
      {$limit: 1}
    ],
    as: 'projects'
  }},
  {$addFields: {project: {$arrayElemAt: ['$projects', 0]}}}
])

0 个答案:

没有答案