Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda