简体   繁体   中英

Android Cloud Firestore efficient way to get few documents from collection

What is the most efficient way to get 3 documents (marked red) from firebase collection? One more obstacle for me is, that user document has auto-generated Id. The code below works but I think is not efficient way to do it. If 'times' collection grows, retrieving whole collection while want only one or two documents doesn't make sense. If there is no way to improve it, any suggestions of modifying my firestore structure to achieve the goal?

在此处输入图像描述

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users")
        .whereEqualTo("userName", "tolek")
        .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        // task - retrieves entire user document with all fields and collections, what I don't want - want only document Id
        if (!task.getResult().getDocuments().isEmpty()) {
            db.collection("users")
                    .document(task.getResult().getDocuments().get(0).getId())
                    .collection("times")
                    .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (!task.getResult().getDocuments().isEmpty()) {
                        for (DocumentSnapshot snapshot : task.getResult().getDocuments()) {
                            Log.d("TAG", "Documents : " + snapshot.getId());
                            //here also I receive whole "times" collection but want only 3 documents
                        }
                    }
                }
            });
        }
    }
});

To simplify the loading of the 3 times documents, you can use an in query :

CollectionReference timesRef =  db.collection("users")
                    .document(task.getResult().getDocuments().get(0).getId())
                    .collection("times");

timesRef.whereIn(FieldPath.documentId(), Arrays.asList("20210225", "20210226", "20210227"));

This works for up to 10 values. If you have more than 10 IDs, you'll need to fire more than one query.

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