Is there a way to count all documents in a collection in FaunaDB?
Say I have a users
collection and I have defined an all_users
index. What is the best way to count all documents in the users
collection in the database?
The all_users
index is no longer needed. Fauna now automatically maintains a built-in default index for each collection, and you can access it via Documents(Collection('<collection>'))
.
You can count all users like so:
Count(Documents(Collection('users')))
Now faunadb offers the count() function in the most recent release which is another option to maintaining an aggregate
https://docs.fauna.com/fauna/current/api/fql/functions/count
The best way is to maintain your own aggregate in transaction with your data updates, so update a counter document when you write your new users. I wrote a blog post about how to do that here: https://blog.fauna.com/using-acid-transactions-to-combine-queries-and-ensure-integrity (See the last example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With