gpt4 book ai didi

javascript - MongoDB - 返回 X 条随机记录

转载 作者:行者123 更新时间:2023-12-01 02:42:31 25 4
gpt4 key购买 nike

在我的 Node.js 服务器中,我尝试从我的集合中返回 4 个随机记录。

这是我当前的代码,问题是当前它从我的集合中返回 0-4 个随机记录,而我想每次返回 4 个(不多不少)随机记录。

db.collection('articles')
.find()
.limit( 4 )
.skip(Math.round(Math.random() * 4))
.sort("date", -1).toArray()

如有任何帮助或建议,我们将不胜感激 - 预先感谢您!

I had a look at some similar questions but they all only seem to generate random records between 0-X records, not a set amount.

最佳答案

您可以使用 $sample 聚合管道。

Randomly selects the specified number of documents from its input.

The $sample stage has the following syntax:

{ $sample: { size: <positive integer> } }

例如此代码返回 4 个随机文档:

db.collection('articles').aggregate([
{ $sample: { size: 4 } }
]);

如果需要选择x按某些标准随机文档,然后只需添加 $match

关于javascript - MongoDB - 返回 X 条随机记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47474009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com