0
Follow
0
View

Display random files from the database

ya313584699 注册会员
2023-01-25 20:44
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

ctl198423 注册会员
2023-01-25 20:44

You can use $sample but from the documentation See

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 the Author

Question Info

Publish Time
2023-01-25 20:44
Update Time
2023-01-25 20:44