Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda