Intelligent Fig
Intelligent Fig11mo ago

Counting total table documents

Is there an easy way to get the total no. of documents for a specific table in convex without scanning the whole table? The use-case is to show “this platform is used by x users” message on the website, where ‘x’ is the total number of documents in Users table. I can think of creating a counter and incrementing it for each user table document addition (counter++) but just wondering if there is any direct way to get the total documents number for a table.
2 Replies
erquhart
erquhart11mo ago
There’s an undocumented count() method that does exactly this. Please understand that it’s undocumented for a reason! It can break or be removed at any time, and shouldn’t be relied upon. Maybe store the count in your own table and update it each time.
// @ts-expect-error
ctx.db.query(‘myTable’).count()
// @ts-expect-error
ctx.db.query(‘myTable’).count()
Also note, though, that keeping your own aggregate count is pretty simple - create a count field, increment on insert, and decrement on delete. Because mutations are transactions, the count will always be accurate.
Intelligent Fig
Intelligent FigOP11mo ago
Makes sense. Thanks!

Did you find this page helpful?