mongo db aggregate randomize ( shuffle ) results

为君一笑 提交于 2021-02-08 04:40:58

问题


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

is there any ?


回答1:


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.

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" } }
);

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.



来源:https://stackoverflow.com/questions/23021475/mongo-db-aggregate-randomize-shuffle-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!