I have a aggregate query I'm using to get the 10 first results of a lookup between 2 collections. I'm only getting the first 10, because if I use no limit and get 50 results the query gets slow (4-5 secs) (any suggestions on that will also be great)
So because Im doing some kind of scan I need to let the client know the number of total results, so it can query more when needed. currently im running the cursor twice and im sure that is not ideal.
const grades = database.collection('grades');
const match = { userId };
const aggregationPipeline = [
{ $match: match},
{ $addFields: { userIdObj: { $toObjectId: '$userId' } } },
{
$lookup: {
from: 'users',
localField: 'userIdObj',
foreignField: '_id',
as: 'userDetails',
},
},
];
const aggCursor = grades.aggregate(aggregationPipeline);
const aggCursorCount = grades.aggregate([...aggregationPipeline, {
$count: 'count',
}]);
const count = await aggCursorCount.toArray();
const allValues = await aggCursor.limit(10).toArray();
res.json({grades: allValues, count: count[0].count});
Im sure there is a more efficient way to get what I need. Still learning all mongodb stuff.
Thanks!