BIS Tech
BIS Tech

Reputation: 19444

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

I am currently using whereIn for this. But only get 10 or less douments at once. whereIn 10 entries or less according to the firestore documentation

Is there any way to get more than 10 documents at once in one round trip?

 return _db
        .collection('books')
        .where('docId', whereIn: ['id1', 'id2'...'id10'])
        .get()
        .then((value) => value.docs.map((e) => BookModel.fromFireStore(e)).toList());

Upvotes: 1

Views: 1021

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317467

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

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

Upvotes: 3

vogdb
vogdb

Reputation: 4829

The question has been answered. Here I just want to show how you can get those documents with multiple round-trips cause it is not an easy task as well. It took me some time to implement this, so I hope it will save someone else's time.

First create a function for one round-trip:

Future<List<Book>> _getBooksByIds(ids) {
  return _instance
      .collection('books')
      .where(FieldPath.documentId, whereIn: ids)
      .get()
      .then((QuerySnapshot snapshot) {
    return snapshot.docs.map((DocumentSnapshot doc) => BookModel.fromSnapshot(doc)).toList();
  });
}

Then split by 10 your ids

ids = ['id1', 'id2'...'id11'];
final idsBy10 = [
  for (var i = 0; i < ids.length; i += 10)
    ids.sublist(i, min(i + 10, ids.length))
];

Then run multiple requests and merge their results:

Future.wait<List<Book>>(idsBy10.map((ids) => _getBooksByIds(ids)))
        .then((listOfLists) => listOfLists.expand((l) => l).toList());

Upvotes: 1

Related Questions