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
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
You can use $sample but from the documentation See
WARNING $sample may output the same document more than once in its result set.
Query
aggregate(
[ {"$sample" : {"size" : 100}},
{"$group" : {
"_id" : "$_id",
"doc" : {"$first" : "$$ROOT"}
}
},
{"$unwind" : {"path" : "$doc"}},
{"$replaceRoot" : {"newRoot" : "$doc"}},
{"$limit" : 15}
])