Tamás Polgár
Tamás Polgár

Reputation: 2262

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

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.

Upvotes: 1

Views: 782

Answers (1)

s7vr
s7vr

Reputation: 75914

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
  }
}]);

Upvotes: 2

Related Questions