0

Let's say I have 9 docs in a collection, 3 of them contains section: 1, 3 of them contains section: 2, 3 of them contains section: 3.

I want to get two random docs that contain section: 2.

something like:

const colRef = collection(db, "readingfiles");

const q = query(colRef, where("section", "==", 2), orderBy("random"), limit(2));

getDocs(q).then((snapshot) => {
    snapshot.docs.forEach((doc) => {
        console.log(doc.data());
    })
}).catch((err) => {
    console.log(err.message);
});

One way I found is to give an Id to every document then use where( ) with random numbers to get data.

I wonder if there is any easy and effective way.
something like:

const q = query(colRef, where("section", "==", 2), getRandom(2));

or

const q = query(colRef, where("section", "==", 2), orderBy("__random__"), limit(2));
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
ækit
  • 411
  • 3
  • 13
  • 1
    Does this answer your question? [Get random documents from Firestore using Javascript](https://stackoverflow.com/questions/68463784/get-random-documents-from-firestore-using-javascript). There isn't any native `getRandomDocuments()` function in Firestore at the moment. – Dharmaraj Feb 14 '22 at 15:26

0 Answers0