-1

im trying to retrieve the number of courses created, the courses created will show in "Courses" collection. this is the code i used

String course = '';
    FirebaseFirestore.instance
        .collection("Courses")
        .get()
        .then((QuerySnapshot querySnapshot) {
      course = querySnapshot.docs.length.toString();
    });

this is a screenshots of my firebase

enter image description here

  • check answer here https://stackoverflow.com/a/49407570/9138027 – Ali Yar Khan Dec 01 '21 at 12:56
  • i looked into it i tried this but it is showing me error with "snap" here FirebaseFirestore.instance.collection('Courses').get().then(snap => { size = snap.size }); –  Dec 01 '21 at 13:00
  • what error ? post the error plz – Ali Yar Khan Dec 01 '21 at 13:01
  • its not recognizing the word snap where so i define it –  Dec 01 '21 at 13:03
  • Your code refers to `Course` (singular) while the database has `Courses` (plural). Since those are not the same, the code will not be reading from the collection shown. – Frank van Puffelen Dec 01 '21 at 15:02
  • fixed that but still not retrieving –  Dec 01 '21 at 15:05
  • Here's the issue; collections don't know how many documents they contain so to get the count you have to retrieve all of the documents to then get a count. That could be time consuming as well as a lot of reading (cost). The simple solution is to keep the count in another collection or at a known document location within the collection. For example, in your screen shot, there are 10 documents in the Courses collection; add a document called `doc_count' with a single field to hold the count of 10. As you add documents, increment that count, as you remove documents decrement the count. – Jay Dec 03 '21 at 19:36
  • mightyleen could you please confirm if the answer given by @Jay was helpful? If it is, could you please, Jay, post it as an answer to help the community? – Vicky Dec 13 '21 at 09:34
  • @Vicky Posted and answer - it should be a good solution for this use case. – Jay Dec 13 '21 at 19:33

2 Answers2

3

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>> courseList = FirebaseFirestore.instance.collection('Courses');

  Future<int> countCourses() async {
    AggregateQuerySnapshot query = await courseList.count().get();
    debugPrint('The number of courses: ${query.count}');
    return query.count;
  }
jbryanh
  • 1,193
  • 7
  • 17
1

Collections don't know how many documents they contain so to get the count you have to retrieve all of the documents to then get a count. That could be time consuming as well as a lot of reading (cost).

The simple solution is to keep the count in another collection or at a known document location within the collection.

Generically speaking, suppose we have three collections, Courses, Users and Locations and each one could have 0 to thousands of documents.

Users
   user_0
      ...some fields
   user_1
      ...some fields

Courses
   course_0
      ...some fields
   course_1
      ...some fields

Locations
   location_0
      ...some fields
   location_1
      ...some fields

As previously mentioned, if there are a limited number of documents simply reading Users (for example) and getting the count of the documents from the snapshot works and is simple. However, as Users grows so does the document count and cost.

The better and scalable solution is to keep anther collection of counts

Document_Counts
   users_collection
      count: 2
   courses_collection
      count: 2
   locations_collection
      count: 2

Then when you want the number of users, simply read the Document_Counts/users_collection document and get the count from the count field.

Firestore has a lighting fast and simple increment and decrement function so as a document is added to Users, for example, increment that same count field.

Jay
  • 34,438
  • 18
  • 52
  • 81