mongodb聚合随机化(shuffle)结果

时间:2014-04-11 19:55:27

标签: mongodb mapreduce shuffle aggregation-framework

我要通过一堆mongo文档,并且找不到随机播放或随机化结果内容的可能性

有没有?

1 个答案:

答案 0 :(得分:1)

特别是对于聚合框架本身而言,实际上没有任何本地方式,因为还没有可用的运算符来执行诸如生成随机数之类的操作。因此,无论你可能投射一个字段进行排序,都不会是真正随机的#34;因为种子价值没有变化。

更好的方法是" shuffle"返回结果后的结果作为数组。有各种各样的" shuffle"实现,这里是一个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的本质,因为键值总是被排序。因此,通过包含一个随机数作为密钥的前导部分,您将始终获得随机排序的结果。

相关问题