Ally Makongo
Ally Makongo

Reputation: 269

Firebase Firestore Document Counts

        db.collection("chatrooms")
                .document(group_name)
                .collection("chats")
                .document()
                .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if(task.isSuccessful()){
                    int size = task.getResult().getData().size();
                }
            }
        });

This does not work on implementation 'com.google.firebase:firebase-firestore:21.0.0'. Any work around will be highly appreciated.

on Firebase database, there was getChildrenCount method, on firestore i can't find any method which can give me count on the documents.

Upvotes: 0

Views: 829

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

The problem is that you're calling document() on the collection:

    db.collection("chatrooms")
            .document(group_name)
            .collection("chats")
            .document()

As the documentation for CollectionReference.document() says:

Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.

So you're loading a single document, which explains why you can't get a count for all documents in the collection.


What you're trying to do is to load all documents in the collection. To do that, you just remove the document() call from your query, and then get a QuerySnapshot object as the result. And the query snapshot has a size method that shows you the number of documents.

So something like:

db.collection("chatrooms")
        .document(group_name)
        .collection("chats")
        .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {

        if(task.isSuccessful()){
            int size = task.getResult().size();
        }
    }
});

While this code technically works, you'll be loading all documents in the collection into the Android app. When you're just getting started that won't be a problem, but as you add more documents it'll be loading more and more data, which is quite wasteful if all you need is the count.

For this reason, most applications also store such counters into the database themselves. For an example of how to do this, see the Firestore documentation on distributed counters.

Upvotes: 1

mvp
mvp

Reputation: 40

You can't do that on a document. If you query a collection, you'll have a list of document snapshots - where you can get the size of the result list.

You'll want to take a look at this: https://stackoverflow.com/a/49407570

Upvotes: 0

Related Questions