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)
它应该是 - Firestore.instance.collection('products').snapshots().length.toString();
首先,你必须从该集合中获取所有文档,然后你可以通过文档列表获取所有文档的长度。下面应该可以完成工作。
Firestore.instance.collection('products').getDocuments.then((myDocuments){
print("${myDocuments.documents.length}");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10147 次 |
| 最近记录: |