是否有任何标准的Firestore查询来获取随机文档? [英] Is there any standard firestore query to get random documents?

查看:35
本文介绍了是否有任何标准的Firestore查询来获取随机文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从动态集合中获取多个随机文档.在不知不觉中,我曾想过使用简单的查询来做到这一点,就像这样:

I am trying to get multiple random documents from a dynamic collection. Until know, I have thought to do it using simple queries, something like this:

 Pseudocode
 
 arr = [];
 while (arr.length < 5) {
     // Start the query at a random position
     startAt = Math.random() * collection.size;
     randomDoc = await dbRef.startAt(startAt).limit(1).get( ... );
     arr.push(randomDoc);
 }

在这里,首先,我必须获取集合的大小,因为它可以是0或更大.然后,使用一种"db随机指针/索引"选择一个随机文档.

Here, firstly, I have to get the collection size, as it can be 0 or bigger. Then, select a random document using a kind of "db random pointer/index".

我的问题是,是否有任何方法可以获得相同的结果,但没有所有循环内容,仅使用查询语法即可.

My question is if there is any way to get the same result but without all the loop stuff, only with the query syntax.

谢谢.

推荐答案

聪明地使用startAt和limit!
您可以在参考中看到没有内置的方法可以返回随机文档.

Clever use of startAt and limit!
As you can see in the reference, there are no built-in methods that would return random documents.

为了避免循环,您可以使用

In order to avoid the loop, you can use Promise.all:

const indices = getRandomIndices(collection.size);
const docs = await Promise.all(indices.map(i => {
    return dbRef.startAt(i).limit(1).get();
}));

对于getRandomIndices,我建议:创建一个数组[0,1,2,...],按照此

And for the getRandomIndices, I suggest: create an array [0, 1, 2, ...], shuffle it as describe in this SO answer, and slice its 5 first elements.

这篇关于是否有任何标准的Firestore查询来获取随机文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆