Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

database - How to get a count of number of documents in a collection with Cloud Firestore

In Firestore, how can I get the total number of documents in a collection?

For instance if I have

/people
    /123456
        /name - 'John'
    /456789
        /name - 'Jane'

I want to query how many people I have and get 2.

I could do a query on /people and then get the length of the returned results, but that seems a waste, especially because I will be doing this on larger datasets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You currently have 3 options:

Option 1: Client side

This is basically the approach you mentioned. Select all from collection and count on the client side. This works well enough for small datasets but obviously doesn't work if the dataset is larger.

Option 2: Write-time best-effort

With this approach, you can use Cloud Functions to update a counter for each addition and deletion from the collection.

This works well for any dataset size, as long as additions/deletions only occur at the rate less than or equal to 1 per second. This gives you a single document to read to give you the almost current count immediately.

If need need to exceed 1 per second, you need to implement distributed counters per our documentation.

Option 3: Write-time exact

Rather than using Cloud Functions, in your client you can update the counter at the same time as you add or delete a document. This means the counter will also be current, but you'll need to make sure to include this logic anywhere you add or delete documents.

Like option 2, you'll need to implement distributed counters if you want to exceed per second


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...