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

问题描述 投票:1回答:1

伙计们,这是一些代码。

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返回所有内容。有没有办法将投影应用于查找结果?我只需要三个领域,titlefirstnamelastname

mongodb aggregation-framework lookup
1个回答
2
投票

$project之后你可以添加一个user阶段来限制来自$lookup数组的字段

db.collection('bugs').aggregate([{
  $project: {
    "user.title": 1,
    "user.firstname": 1,
    "user.lastname": 1
  }
}]);
© www.soinside.com 2019 - 2024. All rights reserved.