Ulabase

Your data

Aggregations

An aggregation computes reports, counts and grouped data in the database; define it once in the console, test it, and call it from your app by name.

An aggregation computes new data from your documents: totals, counts, averages, groups. It is a pipeline, a list of MongoDB stages that MongoDB runs one after the other. You define it once under Aggregations, give it a name, and your app calls it by that name.

Use it for reports and summaries, such as sales by region, orders by status, or the ten most active users.

What you get:

  • Only what you approved. The app calls an aggregation by name and never sends a query of its own.

  • The logic in one place. Every client, web, mobile or an AI agent, gets the same result from the same pipeline.

The Aggregations page

Define one

  1. Open Aggregations and expand the collection.

  2. Click Add aggregation.

  3. Give it a uri: the name it will be called by, unique in the collection. sales-by-region, count-by-status.

  4. Write the stages: the pipeline, as a JSON array.

  5. Test, beside Create or Save, shows what it returns; then save it.

[
  { "$match": { "status": "completed" } },
  { "$group": { "_id": "$region", "total": { "$sum": "$amount" } } },
  { "$sort": { "total": -1 } }
]

The editor helps: Add template starts you off, Add pagination appends $skip and $limit stages driven by parameters, and Format tidies the JSON and points at a mistake. Test executes the pipeline against the collection as it stands, before you save, with the service’s own security checks. It refuses $out and $merge, so it can look but not write.

Saving takes effect at once. The uri cannot be changed afterwards, since it is part of the address your app calls; the stages can.

Rerank the results

With a reranking model set under AI Keys, the form has a Rerank section: tick it, name the query variable (q by default, the parameter that carries the question) and, if you want, how many results to keep. The service hands what the pipeline returns to the model, which reorders it by how well each result answers the question. The model reads each result’s text field, or the whole document when there is none, so add a $set stage that copies the field to judge by into text. See Reranking a search.

Call it from your app

GET /<collection>/_aggrs/<uri>?page=1&pagesize=20
const res = await fetch('https://c0ffee.ulabase.app/orders/_aggrs/sales-by-region', {
  headers: { Authorization: 'Basic ' + btoa('alice:secret') }
});
const rows = await res.json();

The user needs a permission that allows GET on that path, like any other read. Results are paged with page and pagesize.

Parameters

A pipeline can read values from the request with $var, so one definition serves many questions:

[
  { "$match": { "region": { "$var": "region" }, "amount": { "$gt": { "$var": "minAmount" } } } },
  { "$count": "total" }
]

The app passes each one as a query parameter of the same name:

const res = await fetch('https://c0ffee.ulabase.app/orders/_aggrs/sales-by-region?region=europe&minAmount=1000');

A value that looks like JSON is read as JSON: ?tags=[1,2,3] binds an array, ?opts={"limit":10} an object. Anything else is taken as a string, so a bare word needs no quoting.

One kind of variable cannot travel this way: the one whose name is a query parameter the service reads itself, page, sort, filter, keys and the like, which would never reach the pipeline. For those there is the older form: one avars object holding them all.

const avars = encodeURIComponent(JSON.stringify({ sort: { date: -1 } }));
const res = await fetch(`https://c0ffee.ulabase.app/orders/_aggrs/sales-by-region?avars=${avars}`);

Both forms work together in one request, and avars wins if it carries the same name.

In the editor, when the pipeline uses $var, a Parameters for the run box appears. Fill in the ones this pipeline uses writes the skeleton with every name the pipeline reads. $ifvar includes a stage only when a parameter is present; the editor’s Variables and optional stages panel shows both with the predefined names.

Large pipelines

MongoDB gives a pipeline 100 MB of memory. A $group or $sort over millions of documents can exceed it and fail. MongoDB’s way out, allowDiskUse, is not available on Ulabase: it spills the pipeline to the disk of a cluster shared with other services, and a definition that turns it on is refused. Narrow the pipeline with a $match first, and add an index on the fields your $match and $sort stages use: a sort on an indexed field needs no memory at all.

From a script

Aggregations are stored in the collection’s metadata, in the aggrs array, so a script writes them with the rest of the collection’s settings:

Operation API

Read the definitions

GET /<collection>/_meta

Save them

PATCH /<collection> with { "aggrs": [ { "uri": "…​", "stages": […​] } ] }

Run one

GET /<collection>/_aggrs/<uri>?<var>=<value>&page=1&pagesize=20

Do it from the command line

You can keep your aggregations in git and apply them with ulabase setup. The steps below create orders and add the sales-by-region aggregation. The aggregations of a collection are its aggrs list, and the step replaces only its own entry, found by uri:

import { defineSetup, step } from '@ulabase/cli';

// the aggregation, called at /orders/_aggrs/sales-by-region
const salesByRegion = {
  uri: 'sales-by-region',
  stages: [
    { $match: { status: 'completed' } },
    { $group: { _id: '$region', total: { $sum: '$amount' } } },
    { $sort: { total: -1 } },
  ],
};

// read the aggregations saved in the settings of orders
const aggrs = async (service: any): Promise<any[]> =>
  (await (await service.fetch('/orders/_meta')).json()).aggrs ?? [];

export default defineSetup('Reports', [
  // step 1: create the orders collection if it does not exist
  step('orders collection exists', {
    check: ({ service }) => service.collectionExists('orders'),
    apply: ({ service }) => service.createCollection('orders'),
  }),

  // step 2: save the aggregation, unless it is already saved with the same stages
  step('sales-by-region aggregation', {
    async check({ service }) {
      const found = (await aggrs(service)).find(a => a.uri === salesByRegion.uri);
      return JSON.stringify(found?.stages) === JSON.stringify(salesByRegion.stages);
    },
    async apply({ service }) {
      // keep the other aggregations, and replace this one
      const others = (await aggrs(service)).filter(a => a.uri !== salesByRegion.uri);
      await service.fetch('/orders', {
        method: 'PATCH',
        body: JSON.stringify({ aggrs: [...others, salesByRegion] }),
      });
    },
  }),
]);

The step writes the whole aggrs list, with the other aggregations as they were, and leaves the rest of the collection alone.

Use createCollection only for a collection that does not exist yet. On an existing collection it replaces all its settings.

  • Constraints: the same pipeline editor, used to write rules a write cannot break.

  • MCP server: an aggregation you publish becomes a tool an AI agent can call.

  • Permissions: who may call which aggregation.