Finding two random documents within a max range of sorted documents

My goal is to find two random documents. Each document has a rating. The rating difference between these two document doesn’t matter to me. But what matters is the distance is documents between these 2 documents.

Take this list for example. Say I randomly select Person7. Now I want a random document say max 3 documents away from Person7. So in this case it should be either Person4, 5, 6, 8, 9, 10.


     { name: "Person1", rating: 50 },

     { name: "Person2", rating: 55 },

     { name: "Person3", rating: 60 },

     { name: "Person4", rating: 65 },

     { name: "Person5", rating: 70 },

     { name: "Person6", rating: 75 },

     { name: "Person7", rating: 800 },

     { name: "Person8", rating: 850 },

     { name: "Person9", rating: 900 },

     { name: "Person10", rating: 100000 },

     { name: "Person11", rating: 100001 },

     { name: "Person12", rating: 102000 }


I think I would have to aggregate this list but I’m not sure what type of aggregations to run. Also I’m not sure one aggregation is enough. I would maybe need to two this in multiple steps(in a transaction).

Hi @anthon_N_A ,

You probably can hack it through an aggregation with $rand games :

But I would definitely say it will be much easier to calculate your random range of ratings or the needed random list of value the app side . Pass the range or list to a simple query to get those ranked documents