count()

Get the number of values in a Set.

Signature

count(): Int

Description

The count() method gets the number of values in the Set.

Because this method scans the full set, it returns an error if there are more than 16000 documents in the set. This method can timeout for large sets under that limit.

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 a collection history_days field 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

Int

Count of values in the Set.

Examples

Get the number of books in the Book collection.

  1. List the Book documents:

    Books.all()
    {
      data: [
        {
          id: "358933729814511650",
          coll: Books,
          ts: Time("2023-03-11T19:58:49.450Z")
          name": "Book of Ond",
        },
        {
          id: "358933733773934626",
          coll: Books,
          ts: Time("2023-03-11T19:58:53.220Z")
          name: "Book of Two",
        },
        {
          id: "365634774532882466",
          coll: Books,
          ts: Time("2023-05-24T19:52:42.340Z"),
          name: "Book of Three",
        }
      ]
    }
  2. Get a count of the number of documents:

    Books.all().count()
    3

 

Count the Customers documents where the state property is DC:

Customer.where(.address.state == 'DC').count()
3

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!