简体   繁体   中英

How to get the number of Firestore documents in flutter

I am building a flutter app and using 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..

There are two ways:

1)

final int documents = await Firestore.instance.collection('products').snapshots().length;

This returns a value of int. But, if you don't use await, it returns a Future.

2)

final QuerySnapshot qSnap = await Firestore.instance.collection('products').getDocuments();
final int documents = qSnap.documents.length;

This returns a value of 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. 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."

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. This will provide you with the count.

Here is an example that works in 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

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. In order to get the int value you have to use the StreamBuilder widget or 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.

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. Then you can fetch the length from firebase remote configs when you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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