Google Firestore - How to Get Several Documents by Multiple Ids in One Round-Trip

Google Firestore - How to get several documents by multiple ids in one round-trip?

if you're within Node:

https://github.com/googleapis/nodejs-firestore/blob/master/dev/src/index.ts#L978

/**
* Retrieves multiple documents from Firestore.
*
* @param {...DocumentReference} documents - The document references
* to receive.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let documentRef1 = firestore.doc('col/doc1');
* let documentRef2 = firestore.doc('col/doc2');
*
* firestore.getAll(documentRef1, documentRef2).then(docs => {
* console.log(`First document: ${JSON.stringify(docs[0])}`);
* console.log(`Second document: ${JSON.stringify(docs[1])}`);
* });
*/

This is specifically for the server SDK

UPDATE:
"Cloud Firestore [client-side sdk] Now Supports IN Queries!"

https://firebase.googleblog.com/2019/11/cloud-firestore-now-supports-in-queries.html

myCollection.where(firestore.FieldPath.documentId(), 'in', ["123","456","789"])

get multiple docs from firestore by id in single transaction

they are using getAll, but this function is not available in firestore 9 AFAIK.

Yes, the getAll() is a part of server side NodeJS SDK and not Firebase client SDK.

which comes with additional cost as firestore gets billed per request

Firestore reads are charged on number of documents fetched irrespective of how many queries you run i.e. 5 queries fetching 10 documents each will cost same amount of reads as a single query of 50 documents. At most you'll be charged for SSL overhead depending on the connection.

So one way is to execute multiple queries that'll fetch up to 10 documents each with in operator along with Promise.all() to run them in parallel.

Get several ids documents firestore

Getting a document by its identifier should be used when you need a single document or documents you cannot (based on your data architecture) query for. Don't be hesitant to denormalize your data to make queries work, that's the point of NoSQL. If I were you, I'd either add a field to these documents that can be queried or denormalize this data set with a new collection (just for this query). However, if you still choose to fetch multiple documents by identifier, then you need to make n getDocument requests and use a dispatch group to handle the asyncing:

let docIds = ["JtThFuT4qoK4TWJGtr3n", "TL1fOBgIlX5C7qcSShGu", "UkZq3Uul5etclKepRjJF"]

let d = DispatchGroup()

for id in docIds {

d.enter()

Firestore.firestore().collection(...).document(id).getDocument{ (document, error) in

// append to array
d.leave()

}

}

d.notify(queue: .global(), execute: {

// hand off to another array if this table is ever refreshed on the fly

DispatchQueue.main.async {
// reload table
}

})

All the dispatch group does is keep a count of the number of times it's entered and left and when they match, it calls its notify(queue:execute:) method (its completion handler).

Firebase Query, get multiple documents from a single collection where each doc.id is equal to the id in a seperate list

You can do a query for multiple document IDs at once using an "in" query and using FieldPath.documentId():

const array = [...];
const snapshot = await firebase
.firestore()
.collection('posts')
.where(firebase.firestore.FieldPath.documentId(), 'in', array)
.get();

But this only works if the array is of less then 10 items long (Firestore limitation). If you need more, you'll have to either batch the IDs, into smaller arrays and perform multiple queries, or simply iterate the IDs, and get() each document individually (which is just fine, really, don't worry about performance on that).

FireBase Firestore retrieve multiple documents by list of ID's

To simplest way that I can think of is to create a new property to each house object called cityName. So your database structure should look like this:

Firestore-root
|
--- houses (collection)
|
--- houseId (document)
|
--- propertyA: "Property A" (document propery)
|
--- propertyB: "Property B" (document propery)
|
--- cityName: "City Name"

how do i get for each house in this list the name of the city?

Just query your houses collection and get the corresponding city name. In code, should look like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference ref = rootRef.collection("Posts").document("Post");
ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String cityName = document.getString("cityName");
Log.d("TAG", cityName);
} else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});

So there is no need to keep a reference of the city in order to display the city name.

Fetch multiple documents by id in Firestore

Firestore does not currently support query by IDs.

According to AngularFirebase, this is in the roadmap for development in the future, but its not official:

Keep in mind, Firestore is still in beta. Firebase engineers hinted at some really cool features on the roadmap (geo queries, query by array of ids) - I’ll be sure to keep you posted :)

Add multiple documents and receive the ID in Firestore

What you're saying is true - a batch can only write data. It can't read them. If you want to read documents after writing them, you will have to wait for the batch write to finish, then execute queries to read the written documents. There's no simple workaround for this.

How to retrieve data one by one from an array in the Firestore

No, there is not. When you read a document, you always get the entire contents of the document. There is no way to limit that.

Your only workaround is to put each array item in a separate document, and query for only those documents you need.

get more than 10 documents from firestore in one round trip using Flutter

No, 10 is a hard limit and can't be exceeded. You will need to perform multiple queries to get more than 10 documents by ID. The documentation states:

Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR.



Related Topics



Leave a reply



Submit