array.distinct()

This method operates on an array. You typically fetch documents from a collection as a set, not an Array. For the equivalent Set method, see set instance methods.

For differences between Sets and Arrays, see Sets vs. Arrays.

Get the unique elements of an Array.

Signature

distinct() => Array<A>

Description

Gets the unique elements of the calling Array.

The calling Array isn’t changed.

Avoid using distinct() with large Sets

Avoid using distinct() to process Arrays converted from large or unbounded Sets that contain 16,000 or more documents.

If a Set contains 16,000 or more documents, the query requires pagination. array.distinct() would only be able to extract unique elements from each page of results.

Instead, retrieve all field values and process them on the client side. See Get unique field values.

Parameters

None

Return value

Type Description

Array<Generic>

Unique elements in the Array.

Examples

Basic example

[1, 1, 2, 3, 3].distinct()
[
  1,
  2,
  3
]

Enforce unique values in an Array field

You can use array.distinct() in a check constraint with to enforce distinct values within a document’s Array field. For example:

collection Customer {
  ...
  emails: Array<String>

  // Check constraint. `Customer` document writes are
  // only allowed if the `emails` Array field contains no duplicate values.
  check uniqueEmails (.emails.length == .emails.distinct().length)
  ...
}

The check constraint ensures the following document write is rejected:

// Rejected due to check constraint.
Customer.create({
  emails: [
    "john.doe@example.com",
    "john.doe@example.com",
  ]
})
\