Firestore Swift 4:How to Get Total Count of All the Documents Inside a Collection, and Get Details of Each Document

FireStore Swift 4 : How to get total count of all the documents inside a collection, and get details of each document?

this will collect all the document for a collection and print them

db.collection("superUsers").getDocuments() 
{
(querySnapshot, err) in

if let err = err
{
print("Error getting documents: \(err)");
}
else
{
var count = 0
for document in querySnapshot!.documents {
count += 1
print("\(document.documentID) => \(document.data())");
}

print("Count = \(count)");
}
}

FireStore Swift: Accessing counts and document details for use in a table

You forget to reload your UITableView once you got the data from the server so you need to reload your UITableView with:

self.tableView.reloadData()

After the for loop. Because it's an asynchronous call where you need to wait until you got the data from the server.

And your code will look like:

override func viewDidLoad() {
super.viewDidLoad()

let reviewTopic = Firestore.firestore().collection("usersIds").document(userEmail!).collection("reviews")
reviewTopic.getDocuments() {
(QuerySnapshot,err) in

if let err = err {
print("Error getting documents: \(err)");
} else {
for document in QuerySnapshot!.documents {
self.count += 1
print("\(document.documentID) => \(document.data())");
}
print("Count = \(self.count)");
self.tableView.reloadData()
}
print("Count from viewDidLoad: ", self.count) // prints 2
}
}

One more thing you should create a class object and store all the data into a class object and then access that data into your cellforrow and numberofrows method. Or you can use Codable protocol to parse your JSON from server and store the server data.

And with that you can easily manage your UITableView datasource and you can also find out which cell is pressed easily.

Cloud Firestore collection count

Aggregate count query just landed as a preview in Firestore.

Announced at the 2022 Firebase Summit: https://firebase.blog/posts/2022/10/whats-new-at-Firebase-Sumit-2022

Excerpt:

[Developer Preview] Count() function: With the new count function in
Firstore [sic], you can now get the count of the matching documents when you
run a query or read from a collection, without loading the actual
documents, which saves you a lot of time.

Code sample they showed at the summit:

Sample Image

During the Q&A, someone asked about pricing for aggregated queries, and the answer the Firebase team provided was that it'll cost 1 / 1000th of the price of a read (rounded up to the nearest read, see comments below for more details), but will count all records that are part of the aggregate.

Fetch all documents in collection - Firebase Firestore iOS

When querying a collection, you are billed for each document returned from the query.

If possible, instead of pulling in all of the documents and sorting through them to find the ones that you want, you can use the .where() functionality provided by the client SDK.

If you want to save on data usage, since the client SDK does not support partial reads of documents, you can create an HTTPS callable cloud function and only send the desired document data back to the client.

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

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

Firestore creating a day total for data entries

What is understood from the question is that you have a simple JSON for each user. You are tracking user activity in this JSON under the field trackingData. This trackingData Array is appended one element of each user activity event, and this event has some event data and timestamp attached to it.
Now, you want to count user activities/day. IMO, The question is missing a key detail about your use case that is "When do you want to update this count (aka SLA)?"

  1. As soon as the event is registered?
    A cloud function will be the most suitable option here, Just listen for updated documents and trigger the function to upsert this particular day's count by one. This is expensive as you are going to read and update the same document every single time a user event occurs.
  2. End of the day?
    Run a cron job on or after 23:59:59 and calculate the last day's count for each user. You are going to read and update the aggregate document only once a day.
  3. Some other time?
    Same as the end of day one but the cron schedule will be different. You will further optimize reads/updates to your SLA.

DO NOT RELY on the client to do this calculation, because:

  1. If you are sending an event and count update in the same request, it is an unnecessary load and it will fail if one of those two actions fails.

  2. If you are sending two independent requests there will be chances of inconsistency if one of those two will fail.

Cheers!



Related Topics



Leave a reply



Submit