How to pull random item from database

I would like to have a page element that pulls a random item from the database each time the page is accessed.

How can this be done?

I’ll recommend to use math.random() to get a random number and then request the item which index matches that number.

Hi Ryan,

First of all, I would query the entire collection using wixData.query to have an array of your entire collection. After that, like Carlos suggested, I would have generated a random number in the size of the collection
And then, using the generated number as an index in the array.
for example:

  wixData.query("myCollection")
  .find()
  .then( (results) => {
    let randomNumber =  Math.floor((Math.random() * results.items.length)); 
    let randomItem = results.items[randomNumber];
    

Remember that arrays start from index number 0 and the Math.random generates a number between 0 and 1 which is the reason for multiplying it

-Lior

So if anyone’s still out there…this code pulls a random “item” from the database. Then what? Like I have a text box ( in a light box) where i want to display the “item” (which is text). So this code pulls a random line from database, but how do I get the text box on the light box to display that line? Then, I want two other text box to display the “name” and “type” of that line of text (item). I can generate a random item but don’t know how to connect it to the text box. It only gives option to link it to a certain category of the data collection…soooo…where is the “connect” here? Anyone??

I have a question re the above - as wixdataquery limits the results to a default of 50 items, does that mean if you have more than 50 items in the collection you are really only randomising the first 50 with the above code? Iunderstand that you can increase this by using limit() however the max then is 1000. Hypothetically, if you had more than 1000 items in the collection, what would you need to do to say choose a random item from 5000 items?