1

I have a collection that has a bunch of songs each with a value of "index" to state which song is to be played next. How do I preform a Fisher–Yates Shuffle with all document's "index" values?

Example:

[{index:1},{index:2}{index:3}]

to

[{index:2},{index:3}{index:1}]

So far, I have it just grab all of the documents put it in an array do the shuffle and update all values again. But with over 1000 documents i am afraid this is awfully inefficient.

Another idea is to remove index all together and just rely on the collection to keep it organized. This seems the most probable as I can just use $sample to get a random song. But if there is a way to do a proper shuffle with the index values that would be great.

Thanks in advance!

EDIT: This is not a question regarding a way to get a random document from a collection but, a way to shuffle the values within the documents. I am wondering if this is possible to do without the needs of sample or loading the entire database.

RoomofR
  • 11
  • 6
  • Nope. And actually the most efficient thing I can think of you doing here is to basically let `$sample` do the work and then use a `$match` and `$in` on subsequent queries to **exclude** the "played" unique ids in the current cycle, in order to ensure the same thing does not randomly select again. Asking to write to a database in "random order" is not really an efficient thing to ask for. `$sample` has been chosen with the most efficient algorithm as you are going to get. So don't try and re-invent the wheel. – Neil Lunn Aug 08 '17 at 12:50
  • Just to clear that up. `$sample: { "size": 1 }` on each iteration as opposed to keeping an open cursor using `$sample` over the expected number of results. – Neil Lunn Aug 08 '17 at 12:58
  • Well, I guess there is nothing better than just using $sample. Thanks :D – RoomofR Aug 08 '17 at 13:03

0 Answers0