繁体   English   中英

如何从 Firestore 集合中获取所有唯一值?

[英]How to get all unique values from Firestore collection?

我在 Firestore 中有以下集合:

用户(集合)

Users (Collection)
-- user1 (Document)
-----name: "John"
-----age: 23

-- user2 (Document)
-----name: "Mary"
-----age: 25

-- user3 (Document)
-----name: "John"
-----age: 20

问题:如何查询 Firestore 以便获取集合中的所有唯一名称?

期望的结果:(约翰,玛丽)

提前致谢!

没有特定的 API 可以从 Cloud Firestore 中检索唯一值。 您必须检索所有相关文档并确定您自己代码中的唯一名称。

或者,考虑添加一个具有唯一名称的文档,并在每次写入时更新它。 这是 NoSQL 数据库中非常常见的方法,但如果您不熟悉它们,可能需要一些时间来适应。

这就是你可以用javascript v8(也许是admin js sdk)做到这一点:

export const getUniqueFieldValues = async (collection, fieldName) => {
  const uniqueValues = [];
  let lastDoc;

  // without any where on fieldName, firestore would return documents without the field
  const withWhere = collection.where(fieldName, "!=", null);
  const [doc] = (await withWhere.orderBy(fieldName).limit(1).get()).docs;
  lastDoc = doc;
  const fieldValue = doc.get(fieldName);
  uniqueValues.push(fieldValue);

  do {
    // we need a not-in because the doc after `lastDoc` likely has the same value
    const withWhere = collection.where( fieldName, "not-in", uniqueValues.slice(-1));
    // use a db cursor to skip over the documents we know have values we've seen
    const [doc] = (
      await withWhere.orderBy(fieldName).startAfter(lastDoc).limit(1).get()
    ).docs;
    if (!doc) return uniqueValues; // return if we can't find any more unique values
    lastDoc = doc;
    const fieldValue = doc.get(fieldName);
    uniqueValues.push(fieldValue);
    // keep going to find more unique values
  } while (true);
};

如何计算名称属性的每个唯一值在用户集合中出现的次数,如下所示:

db.collection("users").select("name", "COUNT(name) as count").groupBy("name").get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      console.log(doc.data().name, doc.data().count);
    });
  })
  .catch((error) => {
    console.error("Error getting documents: ", error);
  });

这将返回:

John 2
Mary 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM