set.where()

Learn: Sets

Get the elements of a Set that match a provided predicate.

Loading strategy:

Signature

where(predicate: (A => Boolean | Null)) => Set<A>

Description

Returns a Set of elements from the calling Set that match a provided predicate function.

If where() is the last value in a query, the first page of the created Set is returned.

Parameters

Parameter Type Required Description

predicate

Predicate function

Yes

Anonymous predicate function that:

The method returns a Set of elements for which the predicate returns true.

Return value

Type Description

Set<Generic>

Set containing elements of the calling Set that match the predicate. If there are no matching elements, the Set is empty.

Examples

Basic example

Customer.all().where(.address.state == "DC")
{
  data: [
    {
      id: "111",
      coll: Customer,
      ts: Time("2099-10-22T21:56:31.260Z"),
      cart: Order("412483941752112205"),
      orders: "hdW...",
      name: "Alice Appleseed",
      email: "alice.appleseed@example.com",
      address: {
        street: "87856 Mendota Court",
        city: "Washington",
        state: "DC",
        postalCode: "20220",
        country: "US"
      }
    },
    ...
  ]
}

Filter covered index values

You can use set.where() to filter the results of an index call. If the set.where() predicate only accesses fields defined in the index definition’s terms and values, the query is covered.

For example, given the following index definition:

collection Product {
  ...

  index byName {
    terms [.name]
    values [.price, .description]
  }

  ...
}

The following query is covered:

// Covered query.
// Calls the `byName()` index.
// Uses `where()` to filter the results of
// the index call. The predicates only
// access covered terms and values.
Product.byName("limes")
  .where(.description.includes("Conventional"))
  .where(.price < 500) {
    name,
    description,
    price
  }

The following query is uncovered:

Product.byName("limes")
  .where(.description.includes("Conventional"))
  // The `where()` predicate accesses the uncovered
  // `stock` field.
  .where(.stock < 100)
  .where(.price < 500) {
    name,
    description,
    price
  }

To cover the query, add the uncovered field to the index definition’s values:

collection Product {
  ...

  index byName {
    terms [.name]
    // Adds `stock` to the index's values
    values [.price, .description, .stock]
  }

  ...
}
\