Answer the question
In order to leave comments, you need to log in
How to specify only certain fields in $project when combining data using $lookup?
Hello.
There are two collections, when fetching with aggregate, I join the collection with the user by ID
Like this:
return Posts
.aggregate([
{ $match: request.query },
{ $sort: request.sort },
{ $skip: request.skip },
{ $limit: request.limit },
{
$lookup: {
from: 'users',
localField: 'owner',
foreignField: '_id',
as: 'owner'
}
}
])
return Posts
.aggregate([
{ $match: request.query },
{ $sort: request.sort },
{ $skip: request.skip },
{ $limit: request.limit },
{
$lookup: {
from: 'users',
localField: 'owner',
foreignField: '_id',
as: 'owner'
}
}, {
$project: {
_id: 1,
name: 1,
items: 1,
premiumAt: 1,
owner: {
_id: { $arrayElemAt: [ '$owner._id', 0 ] },
username: { $arrayElemAt: [ '$owner.username', 0 ] }
},
photos: { $arrayElemAt: [ '$photos', 0 ] },
comments: { $size: '$comments' }
}
}
])
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question