Check out v4 of the Fauna CLI

v4 of the Fauna CLI is now in beta.

The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start.

set.count()

Get the number of elements in a Set.

Signature

count() => Number

Description

Gets the number of elements in the calling Set.

Eager loading

This method uses eager loading and requires a read of each document in the calling Set. For large Sets, this may result in poor performance and high costs.

Performance hint: full_set_read

Queries that call this method on a document Set emit a performance hint, if enabled. For example, the following query:

// Use `count()` to get a count of all products
Product.all().count()

Emits the following hint:

performance_hint: full_set_read - Using count() causes the full set to be read. See https://docs.fauna.com/performance_hint/full_set_read.
at *query*:2:20
  |
2 | Product.all().count()
  |                    ^^
  |

To address the hint, use set.take() to explicitly limit the size of the calling Set to fewer than 100 documents:

// Limit the doc Set's size using `take()`
Product.all().take(99).count()

This applies even if the original, unbounded Set contains fewer than 100 documents.

Alternatively, you can rewrite the query to avoid calling the method.

Avoid use on large sets

This method scans the full Set, which can cause many reads and might time out for large Sets.

Considerations

A document update stores a new version of the document for which counter data is poorly suited for database storage.

If a frequently updated counter is essential, an event-sourcing technique is recommended to reduce database contention and reduce unnecessary database operations.

If the event sourcing pattern isn’t suitable, the following improvements might be considered:

  • Set the collection’s history_days setting to a small value, with a zero value recommended. Document history continues to be collected, but is removed sooner than the default zero days.

  • Periodically, run a query to explicitly remove document history.

  • Instead of attempting to implement a real-time counter, consider storing countable documents as a cache and periodically analyzing cache contents to update a reporting document.

Parameters

None

Return value

Type Description

Number

Count of values in the Set.

Examples

Get a count Product documents with a name of limes:

Product.all().count()
9

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!