Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FireBase Firestore retrieve multiple documents by list of ID's

I've got two collections for example Cities and Houses. Houses are not a nested collection of Cities, but a house contains a reference to a City.

Wat is the most efficient way to get city information for each house in a list?

For Example

class City {
  var name: String = ""
  var property1: String = ""
  var property2: String = ""
}

class House {
  var cityId: String = ""
  var propertyA: String = ""
  var propertyB: String = ""
}

I've got a list of houses, how do I get for each house in this list the name of the city? Is this possible by query, or should I just get all the cities (or each one seperate) and map them in code.

The cities and houses are just an example, but simular to my real situation.

like image 534
Luciano Avatar asked Nov 04 '25 13:11

Luciano


2 Answers

You can use com.google.firebase.firestore.FieldPath. This is working for me in kotlin:

//friendsIDs is ArrayList<String>
    firestore!!.collection("users").whereIn(FieldPath.documentId(), friendsIDs).get().addOnCompleteListener {usersDocs ->
        if (usersDocs.isSuccessful) {
            val result = usersDocs.result!!
            val docs = result.documents
            for (userDoc in docs) {
                val friendData = userDoc.data!!
                //...
            }
        } else {
            Log.e("FirestoreRequest", "Error getting documents.", usersDocs.exception)
        }
    }
like image 108
Дмитрий Власов Avatar answered Nov 07 '25 09:11

Дмитрий Власов


For a web app (JS), this works: db.collection('myCollection').where(firebase.firestore.FieldPath.documentId(), "in", collectionIds).where('status', '==', 2) where collectionIds is an array of Document IDs.

like image 35
hamx0r Avatar answered Nov 07 '25 09:11

hamx0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!