1

I have Mongo Database, and I want to select a random sample of users, which I found a solution for in different places (including here).

Now, the hard part: How to get a unique and random set of users every time I make a request to mongo that doesn't correlate to the random sample I received in the (at least) last request.

Thanks!

Community
  • 1
  • 1
securecurve
  • 5,589
  • 5
  • 45
  • 80

1 Answers1

0

One idea is to store the used up samples in an array and do your random query with the addition of the not-in-array-elements condition $nin. Below is sample code for demonstrating $nin, which you can edit and play around with on my Saturn Fiddle.

// Welcome to SaturnAPI!
// Start collaborating with MongoDB fiddles and accomplish more.
// Start your code below these comments.

// Create a new collection
var Posts = new Mongo.Collection(null);

//Insert some data
Posts.insert({
  number: 1,
  author: "Saturn Sam", 
  message: "Hello!"
});
Posts.insert({
  number: 2,
  author: "Saturn Sam2", 
  message: "Hello!"
});
Posts.insert({
  number: 3,
  author: "Saturn Sam3", 
  message: "Hello!"
});

// Returns all records
// Posts.find({}).fetch()

// Returns all records with `number` not equal to `2` or `1`
Posts.find({number: {$nin: [2, 1]}}).fetch()
FullStack
  • 5,902
  • 4
  • 43
  • 77
  • If I know which users numbers to exclude, then this is not random :) In my case users numbers to exclude is unknown, and those number is randomly generated – securecurve Sep 13 '15 at 11:04
  • In each query, you want a random set that has not been chosen in previous queries, right – FullStack Sep 13 '15 at 12:03
  • Oh, now I get you. Yes your solutions is correct and doable, but I'm trying to find a more native mongo solution. Appreciated! – securecurve Sep 13 '15 at 16:43
  • That's going to be tough, since you need some memory of previous queries. – FullStack Sep 14 '15 at 02:37
  • If no other solution that's natively done by the Mongodb, then, your solution is the solution, or at least a seed for a solution. I will wait for a while for other answers, if not, I'll have your answer checked! – securecurve Sep 14 '15 at 07:45