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

129
Views
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 answers
Answer question

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 Report

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 Report
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!