Query with a random result?

Say I am doing query to find users that meet a criteria for a contest but I want the result to be random. Is there some way to do so?

I am using the latest version of ParseSwift SDK and I found:

But I have no idea if this is what I am looking for and how to use it. I tried searching in the API to no avail.

One idea can be using the limit() function to return only 1 element, and the skip() function with a random number.

1 Like

Worth to mention. Skip function still make database scan every skipped object. İf you skip 5000 item and return the next 1 item, database will scan 5001 item.

For a few hundred or thousand objects that won’t be a problem but if you skip above certain level objects, performance can decrease. An alternative for that would be skipping objects based on created at value. Create index for created at field and order by ascending or descending doesn’t matter. Then

Query.lessThan(‘createdAt’, randomDate)

Just a suggestion. Like i said you can still use skip if you skip low number.


Isn’t it possible using aggregates with the $sample operator?

edit: assuming you have Parse Server version >= 2.7.1 and MongoDB version >= 3.2.

1 Like

bump. anyone with a good answer? Needing this random function as well. Though I could hack one I think, I’m not sure it’s the most efficient way of doing it.