mongo db聚合随机化(随机播放)结果 [英] mongo db aggregate randomize ( shuffle ) results

查看:44
本文介绍了mongo db聚合随机化(随机播放)结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was going thru bunch of mongo docs and can't find a possibility to shuffle or randomize result content

有吗?

推荐答案

专门针对聚合框架本身,实际上并没有任何本机方式,因为尚无可用的运算符来执行类似生成随机数的操作.因此,由于缺少不断变化的种子值,因此您可以投影出要排序的字段的任何匹配都不会是真正随机的".

Specifically for the aggregation framework itself there is not really any native way as there is no available operator as yet to do something like generate a random number. So whatever match you could possibly project a field to sort on would not be "truly random" for lack of a shifting seed value.

更好的方法是在返回结果后将结果作为数组洗牌".有多种随机播放"实现,以下是JavaScript的一种实现:

The better approach is to "shuffle" the results as an array after the result is returned. There are various "shuffle" implementations, here is one for 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;
}

但是,如果您实际上是在谈论改组大量结果,例如使用新的

But if you are actually talking about shuffling a large number of results such as in a collection obtained from use of the new $out operator or any collection in fact, then you can "cheat" by using mapReduce.

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

这利用了mapReduce的特性,因为键值始终被排序.因此,通过将随机数作为密钥的开头部分,您将始终获得随机排序的结果.

This takes advantage of the nature of mapReduce in that the key value is always sorted. So by including a random number as the leading part of the key then you will always get a random ordered result.

这篇关于mongo db聚合随机化(随机播放)结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆