> ## Documentation Index
> Fetch the complete documentation index at: https://forest-chore-open-api.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Code-based segments

A Segment is a subset of a Collection: it's a saved filter of your Collection.

Segments are designed for those who want to *systematically* visualize data according to specific sets of filters. It allows you to save filter configurations so users don't have to do repetitive actions every day.

## From your back-end

Sometimes, Segment filters are complicated and closely tied to your business. Forest allows you to code how the Segment is computed.

For instance, you might implement a Segment on the `products` collection to allow admin users to see the bestsellers at a glance.

### Example

<Info>
  In the following example, we are making queries using the Forest Query Interface.

  As Forest does not impose any restriction on the handler, you are free to call external APIs or query your database directly instead.
</Info>

The only requirement when implementing a Segment from your back-end is to return a valid `ConditionTree`.

<CodeGroup>
  ```javascript Node.js / Cloud theme={null}
  agent.customizeCollection('products', collection =>
    collection.addSegment('mostPurchased', async context => {
      // Query the ids of the 10 most ordered products.
      const rows = await context.dataSource
        .getCollection('orders')
        .aggregate({}, { operation: 'Count', groups: [{ field: 'product_id' }] }, 10);

      // Return a condition tree which matches those records
      return { field: 'id', operator: 'In', value: rows.map(r => r['product_id']) };
    });
  );
  ```

  ```ruby Ruby theme={null}
  ForestAdmin.customize do
    customize_collection('products') do |collection|
      collection.add_segment('mostPurchased') do |context|
        # Query the ids of the 10 most ordered products.
        rows = context.datasource
          .get_collection('orders')
          .aggregate({}, { operation: 'Count', groups: [{ field: 'product_id' }] }, 10)

        # Return a condition tree which matches those records
        { field: 'id', operator: 'In', value: rows.map { |r| r['product_id'] } }
      end
    end
  end
  ```

  ```ruby Ruby DSL theme={null}
  @create_agent.collection :products do |collection|
    collection.segment 'mostPurchased' do |context|
      # Query the ids of the 10 most ordered products.
      rows = context.datasource
        .get_collection('orders')
        .aggregate({}, { operation: 'Count', groups: [{ field: 'product_id' }] }, 10)

      # Return a condition tree which matches those records
      { field: 'id', operator: 'In', value: rows.map { |r| r['product_id'] } }
    end
  end
  ```
</CodeGroup>
