Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch multiple documents by id in Firestore

I'm currently doing a proof of concept for an Android app with the new Firestore as backend/db. I need to fetch a bunch of documents by their id (they are all in the same collection)

Right now, I'm looping thru the id list and fetching them one by one and storing them in a list which in turn updates a RecycleView in the app. This seems to be a lot of work and it does not perform very well.

What is the correct way to fetch a list of documents from Firestore without having to loop all the ids and getting them one by one?

Right now my code looks like this

   for (id in ids) {
        FirebaseFirestore.getInstance().collection("test_collection").whereEqualTo(FieldPath.documentId(), id)
                .get()
                .addOnCompleteListener {
                    if (it.isSuccessful) {
                        val res = it.result.map { it.toObject(Test::class.java) }.firstOrNull()

                        if (res != null) {
                            testList.add(res)
                            notifyDataSetChanged()
                        }

                    } else {
                        Log.w(TAG, "Error getting documents.", it.exception)
                    }
                }
    }
like image 502
iCediCe Avatar asked Mar 18 '18 11:03

iCediCe


People also ask

Can two documents have the same ID in firestore?

New document with same ID should not be allowed in the same collection. It should be possible to fetch an already existing document from a previous import.

How do I query multiple values in firestore?

Starting with… in queries! With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.

How do I get all documents on firestore?

How do I get documents from Firebase? getFirestore() → Firestore Database. doc() → It takes references of database, collection name and ID of a document as arguments. getDoc() → getDoc() query gets data of a specific document from collection based on references mentioned in the doc() method.


1 Answers

This is the way i'm using until they will add this option

I made that with AngularFire2 but also with the rxfire libary is the same if you are using react or vue. You can map the null items before subscribing if there are some documents that deleted.

const col = this.fire.db.collection('TestCol');
const ids = ['a1', 'a2', 'a3', 'a4'];

const queries = ids.map(el => col.doc(el).valueChanges());
const combo = combineLatest(...queries)
      .subscribe(console.log)
like image 199
Lagistos Avatar answered Sep 18 '22 00:09

Lagistos