5

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

is there any ?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
M.Z.
  • 405
  • 6
  • 17
  • You are probably better off shuffling it after you receive it, rather than forcing the DB to do it for you. – Aboba Apr 11 '14 at 20:03
  • 1
    possible duplicate of [Random record from MongoDB](http://stackoverflow.com/questions/2824157/random-record-from-mongodb) – Will Shaver Apr 11 '14 at 20:03
  • but if you are using ->limit(10) - you can get random only from last 10 – M.Z. Apr 14 '14 at 20:11

1 Answers1

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317