Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
mongodb - get first X results and overall count of aggregate function

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!