如何在flutter中获取Firestore文档的数量

aaw*_*223 7 dart firebase flutter google-cloud-firestore

我正在构建一个 Flutter 应用程序并使用 Cloud Firestore。我想获取数据库中所有文档的数量。

我试过

Firestore.instance.collection('products').toString().length
Run Code Online (Sandbox Code Playgroud)

但它没有用。

Mit*_*ick 10

Firebase 没有正式提供任何函数来检索集合中的文档数量,相反,您可以获取集合中的所有文档并获取其长度。

有两种方法:

1)

final int documents = await Firestore.instance.collection('products').snapshots().length;
Run Code Online (Sandbox Code Playgroud)

这会返回一个 int 值。但是,如果你不使用await,它会返回一个Future。

2)

final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;
Run Code Online (Sandbox Code Playgroud)

这会返回一个 int 值。

但是,这两种方法都会获取集合中的所有文档并对其进行计数。

谢谢


jbr*_*anh 10

Cloud Firebase 2.0 提供了一种计算集合中文档数量的新方法。根据参考注释,计数不计为每个文档的读取,而是计为元数据请求:

“[AggregateQuery] 表示特定位置的数据,用于检索元数据,而不检索实际文档。”

例子:

final CollectionReference<Map<String, dynamic>> productList = FirebaseFirestore.instance.collection('products');

      Future<int> countProducts() async {
        AggregateQuerySnapshot query = await productList.count().get();
        debugPrint('The number of products: ${query.count}');
        return query.count;
      }
Run Code Online (Sandbox Code Playgroud)


anm*_*ail 5

它应该是 - Firestore.instance.collection('products').snapshots().length.toString();

  • 请注意,这将导致客户端下载集合中的所有文档只是为了获取计数。对于大型集合,这可能非常低效且成本高昂。 (3认同)
  • @Olantobi 推荐的解决方案在文档中。https://firebase.google.com/docs/firestore/solutions/counters (2认同)
  • 这会返回一种 Future&lt;int&gt; 类型,那么您该如何处理它呢?在您提供的示例中,它甚至没有作为字符串的价值,因为它只是显示错误,并且字符串的值为“Instance of Future&lt;int&gt;” (2认同)

san*_*jay 1

首先,你必须从该集合中获取所有文档,然后你可以通过文档列表获取所有文档的长度。下面应该可以完成工作。

Firestore.instance.collection('products').getDocuments.then((myDocuments){
 print("${myDocuments.documents.length}");
});
Run Code Online (Sandbox Code Playgroud)

  • 如果每个集合中有数千个文档怎么办? (5认同)