【问题标题】:mongo db aggregate randomize ( shuffle ) resultsmongodb 聚合随机化 ( shuffle ) 结果
【发布时间】:2014-04-12 12:29:28
【问题描述】:

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

有吗?

【问题讨论】:

  • 你最好在收到后改组,而不是强迫数据库为你做。
  • Random record from MongoDB 的可能重复项
  • 但如果你使用 ->limit(10) - 你只能从最后 10 个获得随机数

标签: mongodb mapreduce shuffle aggregation-framework


【解决方案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 的特性,即键值始终是排序的。因此,通过包含一个随机数作为密钥的前导部分,您将始终得到一个随机排序的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多