這個問題在這里已經有了答案: 來自 MongoDB 的隨機記錄 29 個答案 昨天關門。
我只需要通過 node/express.js 從 MongoDB 獲取 4 個檔案。我可以限制 4 個檔案,但不能限制隨機 4 。那么,我怎樣才能得到 4 個隨機檔案?
uj5u.com熱心網友回復:
從 MongoDB 的 3.2 版本開始,您可以使用$sample聚合管道運算子從集合中獲取 N 個隨機檔案:
// Get one random document from the mycoll collection.
db.mycoll.aggregate([{ $sample: { size: 1 } }])
如果要從集合的過濾子集中選擇隨機檔案,請在管道前添加 $match 階段:
// Get one random document matching {a: 10} from the mycoll collection.
db.mycoll.aggregate([
{ $match: { a: 10 } },
{ $sample: { size: 1 } }
])
當 size 大于 1 時,回傳的檔案樣本中可能存在重復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414140.html
標籤:
