MongoDB: 是否可以将 $lookup 的结果限制在某些字段(作为投影)?

MongoDB: Is it possible to limit the results of $lookup to certain fields (as a projection)?

伙计们,这是一些代码。

db.collection('bugs').aggregate([{
  $match: finder
}, {
  $sort: { name: 1 }
}, {
  $limit: startrecord + settings.pagination_limit
}, {
  $skip: startrecord
}, {
  $lookup: {
    from: 'users',
    localField: 'user',
    foreignField: '_id',
    as: 'user'
  }
}], {
  collation: collation
}, function(err, docs) {

它工作得很好,它是一个简单的查找。但是,我只需要集合 "users" 中的几个字段,以及 $lookup returns 的所有内容。有没有办法将投影应用于查找结果?我只需要三个字段,titlefirstnamelastname.

您可以在 $lookup

之后添加一个 $project 阶段来限制来自 user 数组的字段
db.collection('bugs').aggregate([{
  $project: {
    "user.title": 1,
    "user.firstname": 1,
    "user.lastname": 1
  }
}]);