0

I first want to determine the length of my collection (i.e. how many documents are in my collection?) and then randomly grab one of the documents and display certain fields in it.

In my Scaffold I have the following StreamBuilder so far:

 StreamBuilder(
          stream: _wordsFoods.snapshots(),
          builder: (context, snapshot){
            return _buildList(context, snapshot.data.documents);
      }
)

_buildList returns the length of the collection "words":

Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot)  {
    return Center(child: Text(snapshot.length.toString()));
  }

But how do I now say that I want the (e.g.) second document in my collection? How do I connect it with a query, so I can say I want a certain field within the second document of my collection?

Marc Köhler
  • 83
  • 2
  • 10

1 Answers1

2

There is no built-in count operation in Cloud Firestore. To determine the number of documents, you either have to retrieve all of them, or keep a separate counter. Since retrieving all documents to determine a number is highly wasteful of bandwidth, most developers go for the second option where they implement a counter field in a separate document in their database, and then update that on every add/delete operation.

There also is no operation to get a document at a certain offset in the client-side SDKs for Firestore. And while the server-side Admin SDKs do offer an offset() method, this one under the hood actually reads all documents that you're telling it to skip. So while it saves on bandwidth for those document, they are still read and charged to your quota.

To efficiently retrieve a random document from Firestore, have a look at Dan's answer here: Firestore: How to get random documents in a collection

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Is it the same thing when trying to get the document by document id from firestore in terms of efficiency ? Like internally is it doing the same as searching through document and matching their id? – Nadeem Siddique May 11 '19 at 15:03