Query on collections

This tutorial shows you how to retrieve documents using FQL’s Collection methods. The example queries use Fauna’s demo data.

Get all documents in a collection

Use all() to get all documents in a collection. Results are returned as a Set.

Store.all()
{
  data: [
    {
      id: "392792530554454082",
      coll: Store,
      ts: Time("2024-03-19T13:29:58.160Z"),
      name: "DC Fruits",
      address: {
        street: "13 Pierstorff Drive",
        city: "Washington",
        state: "DC",
        zipCode: "20220"
      }
    },
    ...
  ]
}

Using all() to search or sort documents isn’t typically performant. Use Indexes instead.

The results of an all() call may be too large to return. In these cases, you’ll need to paginate results instead.

Filter documents in a collection

Use where() to filter a collection’s documents.

The following query returns a Set of documents in the Store collection with a name of Party Supplies.

Store.where(.name == "Party Supplies")
{
  data: [
    {
      id: "392792530555502658",
      coll: Store,
      ts: Time("2024-03-19T13:29:58.160Z"),
      name: "Party Supplies",
      address: {
        ...
      }
    }
  ]
}

Like all(), using where() to search or filter a collection isn’t typically performant. Use Indexes instead.

Get document data using projection

By default, the all() and where() methods return all document fields. You can use projection to only return specific fields.

The following query only returns the name and address.state fields for Store documents.

Store.all() { name, address { state } }
{
  data: [
    {
      name: "DC Fruits",
      address: {
        state: "DC"
      }
    },
    ...
  ]
}

You can also use field aliasing to rename fields in the returned Set. Reference the existing fields using field accessors.

The following query renames the address.state field to myState.

Store.all() { myState: .address.state }
{
  data: [
    {
      myState: "DC"
    },
    ...
  ]
}

Transform results using Set methods

Many collection methods return a Set. This lets you chain Set instance methods to the query to transform returned documents.

For example, the following query chains the <Set>.map() method to <Collection>.all(). <Set>.map() applies a function to each document in the collection.

Store.all()
  .map(store => store.name + " is located at " + store.address.street)
{
  data: [
    "DC Fruits is located at 13 Pierstorff Drive",
    "Party Supplies is located at 7529 Capitalsaurus Court",
    "Foggy Bottom Market is located at 4 Florida Ave"
  ]
}

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!