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

瘦欲@ 提交于 2019-12-24 07:39:22

问题


Here is some code, guys.

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) {

It works perfectly, it's a plain lookup. However I only need a few fields from the collection "users", and the $lookup returns everything. Is there a way to apply a projection to the lookup results? I only need three fields, title, firstname and lastname.


回答1:


You can add a $project stage to limit the fields from user array after $lookup

db.collection('bugs').aggregate([{
  $project: {
    "user.title": 1,
    "user.firstname": 1,
    "user.lastname": 1
  }
}]);


来源:https://stackoverflow.com/questions/42259243/mongodb-is-it-possible-to-limit-the-results-of-lookup-to-certain-fields-as-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!