MongoDB 聚合操作随机化(洗牌)结果。

5

我看了很多Mongo文档,但没找到如何对结果内容进行随机排序的方法。

有没有这样的功能呢?


你最好在收到数据后自己打乱顺序,而不是强制让数据库为你打乱。 - Aboba
1
可能是MongoDB中的随机记录的重复问题。 - Will Shaver
但是如果您使用->limit(10),则只能从最后10个中获取随机数。 - M.Z.
1个回答

1
针对聚合框架本身,由于当前还没有可用的操作符来生成随机数,因此实际上没有任何原生方式可以实现。因此,无论您可能投影出哪个匹配字段进行排序,都不会是“真正随机”的,因为缺乏移动种子值的方法。
更好的方法是在返回结果后将结果作为数组“洗牌”。有各种不同的“洗牌”实现方法,这里是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的特性,即键值总是排序的。因此,通过在键的前面包含一个随机数,您将始终获得一个随机排序的结果。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接