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.

collection.firstWhere()

Get the first collection document that matches a provided predicate.

Signature

firstWhere(pred: (<Document> => Boolean)) => <Document> | <NullDoc>

Description

Gets the first collection document that matches a provided predicate function.

Performance hint: collection_scan

Queries that call this method emit a performance hint, if enabled. For example:

performance_hint: collection_scan - Using firstWhere() on collection Product can cause a read of every document. See https://docs.fauna.com/performance_hint/collection_scan.
at *query*:1:19
  |
1 | Product.firstWhere(.name == "limes")
  |                   ^^^^^^^^^^^^^^^^^^
  |

To address the hint, create an index definition with a terms to look up matching documents instead. For example:

collection Product {
  ...
  // Adds `name` as an index term
  index byName {
    terms [.name]
    values [.name, .price, .description, .stock]
  }
  ...
}

Then call the index in your query. Pass an argument for each term in the index definition. To avoid other performance hints, only project or map field values covered by the index definition’s values:

// Get the first product named "limes"
Product.byName("limes").first() {
  name,
  price,
  description,
  stock
}

Parameters

Parameter Type Required Description

pred

Predicate function

Yes

Anonymous predicate function that:

  • Accepts a collection document as its only argument. Supports shorthand-syntax.

  • Returns a Boolean value.

The method returns the first collection document for which the predicate returns true.

Return value

One of:

Type Description

Document

The first collection document that matches the predicate.

NullDoc

Document doesn’t exist. Returned when no collection document matches the predicate. See NullDoc.

Examples

Product.firstWhere(.stock < 20)
{
  id: "999",
  coll: Product,
  ts: Time("2099-07-30T21:56:38.130Z"),
  name: "taco pinata",
  description: "Giant Taco Pinata",
  price: 2399,
  stock: 10,
  category: Category("123")
}

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!