gpt4 book ai didi

mongodb - mongodb 聚合随机化(洗牌)结果

转载 作者:可可西里 更新时间:2023-11-01 10:43:49 26 4
gpt4 key购买 nike

我正在浏览一堆 mongo 文档,但找不到对结果内容进行随机化或随机化的可能性

有没有?

最佳答案

特别是对于聚合框架本身,实际上并没有任何本地方法,因为目前还没有可用的运算符来执行生成随机数之类的操作。因此,由于缺少不断变化的种子值,您可以投影一个字段进行排序的任何匹配都不会是“真正随机的”。

更好的做法是在返回结果后将结果作为一个数组“打乱”。有多种“随机播放”实现,这里是 JavaScript 的一个:

function shuffle(array) {
var currentIndex = array.length
, temporaryValue
, randomIndex
;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}

但如果您实际上是在谈论对大量结果进行混洗,例如在使用新的 $out 获得的集合中实际上是运算符或任何集合,那么您可以使用 mapReduce“作弊”。

db.collection.mapReduce(
function(){
var random = Math.floor( Math.random() * 100000 );
emit({ rand: random, id: this._id }, this );
},
function(){},
{ out: { replace: "newcollection" } }
);

这利用了 mapReduce 的特性,因为键值总是排序的。因此,通过包含一个随机数作为 key 的前导部分,您将始终获得随机排序的结果。

关于mongodb - mongodb 聚合随机化(洗牌)结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021475/

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