【发布时间】:2022-01-17 17:49:04
【问题描述】:
我只需要通过 node/express.js 从 MongoDB 获取 4 个文档。我可以限制 4 个文档,但不能限制随机 4 。那么,我怎样才能得到 4 个随机文档?
【问题讨论】:
标签: javascript node.js mongodb express
我只需要通过 node/express.js 从 MongoDB 获取 4 个文档。我可以限制 4 个文档,但不能限制随机 4 。那么,我怎样才能得到 4 个随机文档?
【问题讨论】:
标签: javascript node.js mongodb express
从 MongoDB 3.2 版本开始,您可以使用 $sample 聚合管道运算符从集合中获取 N 个随机文档:
// Get one random document from the mycoll collection.
db.mycoll.aggregate([{ $sample: { size: 1 } }])
// Get one random document matching {a: 10} from the mycoll collection.
db.mycoll.aggregate([
{ $match: { a: 10 } },
{ $sample: { size: 1 } }
])
【讨论】: