[英]How to get the number of Firestore documents in flutter
I am building a flutter app and using Cloud Firestore.我正在构建一个 flutter 应用程序并使用 Cloud Firestore。 I want to get the number of all documents in the database.
我想获取数据库中所有文档的数量。
I tried我试过了
Firestore.instance.collection('products').toString().length
but it didn't work.但它没有用。
它应该是 - Firestore.instance.collection('products').snapshots().length.toString();
Firebase doesn't officially give any function to retrieve the number of documents in a collection, instead you can get all the documents of the collection and get the length of it.. Firebase 没有正式提供任何函数来检索集合中的文档数量,相反,您可以获取集合的所有文档并获取它的长度。
There are two ways:有两种方式:
1) 1)
final int documents = await Firestore.instance.collection('products').snapshots().length;
This returns a value of int.这将返回一个 int 值。 But, if you don't use await, it returns a Future.
但是,如果您不使用 await,它会返回一个 Future。
2) 2)
final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;
This returns a value of int.这将返回一个 int 值。
However, these both methods gets all the documents in the collection and counts it.但是,这两种方法都会获取集合中的所有文档并对其进行计数。
Thank you谢谢
Future<int> getCount() async {
int count = await FirebaseFirestore.instance
.collection('collection')
.get()
.then((value) => value.size);
return count;
}
With Cloud Firebase 2.0, there is a new way to count documents in a collection.在 Cloud Firebase 2.0 中,有一种计算集合中文档的新方法。 According to reference notes, the count does not count as a read per document but a metaData request:
根据参考说明,计数不计为每个文档的读取,而是元数据请求:
"[AggregateQuery] represents the data at a particular location for retrieving metadata without retrieving the actual documents." “[AggregateQuery] 表示特定位置的数据,用于在不检索实际文档的情况下检索元数据。”
Example:例子:
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;
}
First, you have to get all the documents from that collection, then you can get the length of all the documents by document List.首先,您必须从该集合中获取所有文档,然后您可以通过文档列表获取所有文档的长度。 The below could should get the job done.
下面应该可以完成工作。
Firestore.instance.collection('products').getDocuments.then((myDocuments){
print("${myDocuments.documents.length}");
});
Future getCount({String id}) async => Firestore.instance
.collection(collection) //your collectionref
.where('deleted', isEqualTo: false)
.getDocuments()
.then((value) {
var count = 0;
count = value.documents.length;
return count;
});
this is in dart language...这是飞镖语言...
Since you are waiting on a future, this must be place within an async function由于您正在等待未来,因此必须将其放置在异步函数中
QuerySnapshot productCollection = await
Firestore.instance.collection('products').get();
int productCount = productCollection.size();
Amount of documents in the collection集合中的文档数量
Instead of getting all the documents using get() or snapshots() and counting them, we can use Firebase Aggregation Queries.我们可以使用 Firebase 聚合查询,而不是使用 get() 或 snapshots() 获取所有文档并对它们进行计数。 This will provide you with the count.
这将为您提供计数。
Here is an example that works in Flutter:这是一个适用于 Flutter 的示例:
final collection = FirebaseFirestore.instance.collection("products");
final query = collection.where("status", isEqualTo: "active");
final countQuery = query.count();
final AggregateQuerySnapshot snapshot = await countQuery.get();
debugPrint("Count: ${snapshot.count}");
You can find more details here: https://firebase.google.com/docs/firestore/query-data/aggregation-queries您可以在此处找到更多详细信息: https://firebase.google.com/docs/firestore/query-data/aggregation-queries
Most Simplest Way:最简单的方法:
int count = await FirebaseFirestore.instance.collection('Collection_Name').get().then((value) => value.size);
print(count);
You want to fetch data from firebase so the call will return a Future.您想要从 firebase 中获取数据,因此该调用将返回一个 Future。 In order to get the int value you have to use the StreamBuilder widget or FutureBuilder.
为了获得 int 值,您必须使用 StreamBuilder 小部件或 FutureBuilder。
For example:例如:
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("<collection name>").getStream().snapshot(),
builder: (context, snapshot) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Stack(children: [
Text(
"${snapshot.data!.docs.length}"
)
]));
});
} }
Firestore.instance
.collection("products")
.get()
.then((QuerySnapshot querySnapshot) {
print(querySnapshot.docs.length);
});
@2022 Using the recent version of FirebaseFirestore you can now get the count without retrieving the entire collection. @2022使用最新版本的 FirebaseFirestore,您现在无需检索整个集合即可获得计数。
CollectionReference ref = FirebaseFirestore.instance.collection('collection');
int count = (await ref.count().get()).count;
Above suggestions will cause the client to download all of the documents in the collection to get the count.以上建议将导致客户端下载集合中的所有文档以获取计数。 As a workaround, if your write operations are not frequently happening, you can put the length of the documents to firebase remote config and change it whenever you add/delete documents from the Firestore collection.
作为一种解决方法,如果您的写入操作不经常发生,您可以将文档的长度放入 firebase 远程配置,并在您从 Firestore 集合中添加/删除文档时更改它。 Then you can fetch the length from firebase remote configs when you need it.
然后,您可以在需要时从 firebase 远程配置中获取长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.