router.get("/alw"/span>, function(req, res){
Product.find({"category"。"alw"}, function(err, allProduct){
if (err){
console.log(err)
} else {
res.render("products/alw"/span>, {products: allProduct})
}
});
});
我想從資料庫中隨機顯示約12-15個產品,而不是一個產品出現兩次。 請告訴我如何去做,因為它令人困惑
。uj5u.com熱心網友回復:
router.get("/alw"/span>, function(req, res){
產品。 aggregate([{$sample:{size: 15}], function(err, allProduct){
if (err){
console.log(err)
} else {
res.render("products/alw"/span>, {products: allProduct})
}
});
});
所以我做了一個研究,并想出了解決方案。所以你可以使用yourCollection.aggregation([{$sample:{size:numberOfObjectsToBeDisplayed}}]);而不是yourCollection.find()因為后者渲染了資料庫中的一切,而前者則是隨機選擇
uj5u.com熱心網友回復:
你可以使用$sample,但是從檔案中看 Query
標籤:
警告 $sample 可能在其結果集中多次輸出相同的檔案。
aggregate(
[ {"$sample" : {"size" : 100},
{"$group" : {
"_id"/span> : "$_id"/span>,
"doc" : {"$first" : "$ROOT"}。
}
},
{"$unwind" : {"path" : "$doc"},
{"$replaceRoot"/span> : {"newRoot"/span> : "$doc"/span>}}。
{"$limit" : 15}.
])
