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

134
Vistas
Display random files from the database
router.get("/alw", function(req, res){
    Product.find({"category": "alw"}, function(err, allProduct){
        if (err){
            console.log(err)
        } else {
            res.render("products/alw", {products: allProduct})
        }
    });
});

I want to display about 12-15 random products from the database without one occuring twice. Please how do i go about it cus its confusing

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

router.get("/alw", function(req, res){
    Product.aggregate([{$sample:{size:15}}], function(err, allProduct){
        if (err){
            console.log(err)
        } else {
            res.render("products/alw", {products: allProduct})
        }
    });
});

So I did a research and came up with the solution. So You can use yourCollection.aggregate([{$sample:{size:numberOfObjectsToBeDisplayed}}]); instead of yourCollection.find() because the later renders everything from the database while the former selects at random

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use $sample but from the documentation See
WARNING $sample may output the same document more than once in its result set.

Query

  • sample like 100 to be sure
  • group to keep unique only
  • limit 15
aggregate(
[ {"$sample" : {"size" : 100}},
  {"$group" : {
    "_id" : "$_id",
    "doc" : {"$first" : "$$ROOT"}
    }
  },
  {"$unwind" : {"path" : "$doc"}},
  {"$replaceRoot" : {"newRoot" : "$doc"}},
  {"$limit" : 15}
])
about 4 years ago · Juan Pablo Isaza Denunciar
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