Und*_*doX 2 android dart flutter
我想计算一个集合中有多少文档,而不是文档的长度。我已经用一些代码尝试过,但出现的是我的文档名称中字符的长度。
这是我的代码:
StreamSubscription<DocumentSnapshot> userpost;
final DocumentReference documentReference =
Firestore.instance.document("product/$documentPost");
userpost = documentReference.snapshots().listen((datasnapshot) {
if (datasnapshot.exists) {
for (int i = 0; i < datasnapshot.data.length; i++){
print(datasnapshot.data.length);
}
Run Code Online (Sandbox Code Playgroud)
Nul*_*e08 13
您可以使用count()cloud_firestore版本4.0.0中添加的功能
接受的答案可能是一个糟糕的解决方案,因为您必须获取所有文档才能计算文档数量。根据Firestore 定价,每个读取的文档均视为 1 次读取计数。
所以更好的解决方案是使用该count()函数来代替。
AggregateQuerySnapshot query = FirebaseFirestore.instance.collection('random_collection').count().get();
int numberOfDocuments = query.count;
Run Code Online (Sandbox Code Playgroud)
count()是一个聚合查询
PS:您可能需要更新 pubspec.yaml 中的 firebase 插件。
anm*_*ail 10
获取文档计数的示例函数。
void countDocuments() async {
QuerySnapshot _myDoc = await Firestore.instance.collection('product').getDocuments();
List<DocumentSnapshot> _myDocCount = _myDoc.documents;
print(_myDocCount.length); // Count of Documents in Collection
}
Run Code Online (Sandbox Code Playgroud)
Cloud Firebase 2.0 提供了一种计算集合中文档数量的新方法。根据参考注释,计数不计为每个文档的读取,而是计为元数据请求:
“[AggregateQuery] 表示特定位置的数据,用于检索元数据,而不检索实际文档。”
例子:
final CollectionReference<Map<String, dynamic>> userList = FirebaseFirestore.instance.collection('users');
Future<int> countUsers() async {
AggregateQuerySnapshot query = await userList.count().get();
debugPrint('The number of users: ${query.count}');
return query.count;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5161 次 |
| 最近记录: |