Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting all documents in a FaunaDB collection

Tags:

faunadb

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?

Update: expanding on @Keston's answer below

  1. 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>')).

  2. You can count all users like so:

Count(Documents(Collection('users')))
like image 329
naartjie Avatar asked Sep 18 '25 09:09

naartjie


2 Answers

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

like image 60
Keston Avatar answered Sep 23 '25 13:09

Keston


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)

like image 43
J Chris A Avatar answered Sep 23 '25 11:09

J Chris A