问题
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