Cloud Firestore collection count

后端 未结 17 1339
庸人自扰
庸人自扰 2020-11-22 09:25

Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

If so, how do I do that?

17条回答
  •  死守一世寂寞
    2020-11-22 09:47

    Solution using pagination with offset & limit:

    public int collectionCount(String collection) {
            Integer page = 0;
            List snaps = new ArrayList<>();
            findDocsByPage(collection, page, snaps);
            return snaps.size();
        }
    
    public void findDocsByPage(String collection, Integer page, 
                               List snaps) {
        try {
            Integer limit = 26000;
            FieldPath[] selectedFields = new FieldPath[] { FieldPath.of("id") };
            List snapshotPage;
            snapshotPage = fireStore()
                            .collection(collection)
                            .select(selectedFields)
                            .offset(page * limit)
                            .limit(limit)
                            .get().get().getDocuments();    
            if (snapshotPage.size() > 0) {
                snaps.addAll(snapshotPage);
                page++;
                findDocsByPage(collection, page, snaps);
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    
    • findDocsPage it's a recursive method to find all pages of collection

    • selectedFields for otimize query and get only id field instead full body of document

    • limit max size of each query page

    • page define inicial page for pagination

    From the tests I did it worked well for collections with up to approximately 120k records!

提交回复
热议问题