0

According to THIS answer ,which explains how to get random items, I can get list of random items from my Mongo database. My question is: How to get only the the first item randomly and the rest of items are in sequence to the first random item.

eg. if having a list of numbers [ 1,2,3,4,5,6,7,8,9,10 ]

and the random selection of the first item has become to be 4, then the rest of the items should be 5,6,7, .. etc.

The hard point of this question is to do this in one query not 2 queries: (1- get one item randomly, then, 2- find all items in sequence with bigger id)

How to do this in one query?

Community
  • 1
  • 1
securecurve
  • 5,589
  • 5
  • 45
  • 80
  • 1
    It is simply not possible in a single query. The basic process for finding a "random" record is explained in answers to [Random Record from MonogDB](http://stackoverflow.com/q/2824157/5031275) meaning essentially find the "min" and "max" values and then get a "random" value in between them. Generally that means multiple queries anyway. But once you have that value then you just use [`$gte`](http://docs.mongodb.org/manual/reference/operator/query/gte/) to get the consecutive values ( with an optional sort if required ). So that question basically still is your answer. – Blakes Seven Oct 15 '15 at 09:43
  • Bottom line is unless you already have the "min" and "max" values, you are querying the collection for those first. The suggestion is to store those values in a cache. – Blakes Seven Oct 15 '15 at 09:44
  • @BlakesSeven, Thanks for your comment, I already referred to this SO question in the first line of my question, I was looking for something else. Anyway, your answer seems to be reasonable, but I'm still looking for some new idea ;) – securecurve Oct 15 '15 at 10:09
  • 1
    Which I already told you there is no new idea ( or at least not one that applies to your scenario ) so your question is still basically the same one that you already referenced. Just because it's a few years old does not mean anything has changed, nor will change for the scenario you describe. Which is also why you are seeing the banner here to confirm the duplicate. – Blakes Seven Oct 15 '15 at 10:13

0 Answers0