Mongster

Aggregation Reference

AggregateQuery method signatures and return types

Model.aggregate(options?) returns an AggregateQuery builder. Each stage is type-aware where it can be and infers the result shape so the next stage (and exec()) sees the right document.

For workflows and design guidance, see the Aggregation guide.

Common stages

StageMethod signatureWhat it produces
match.match(filter: MongsterFilter<Doc>)Same shape, narrows the type via the filter.
group.group(_id, spec: Record<string, GroupAccumulator<Doc>>)New shape keyed by _id with accumulator results.
sort.sort(sort: SchemaSort<Doc>)Same shape, reorders results.
limit.limit(n)Same shape, caps results.
skip.skip(n)Same shape, drops the first n results.
project.project(spec)Reshaped to the projection's inferred shape.
unwind.unwind(path, options?)Unwinds an array field into separate documents.
lookup.lookup({ from, localField, foreignField, as })Joins another Mongster model's collection.
addFields.addFields(fields: AddFieldsStage<Doc>)Adds computed fields.
count.count(name?: string)Reduces to { [name]: number }.

Escape hatch

StageMethod signatureWhat it produces
raw.raw<ReturnType>(stage)Inserts any stage the typed builder does not model. You take responsibility for the shape, including the ReturnType parameter.

Method notes

match(filter)

Throws QueryError if filter is not a plain object.

group(_id, spec)

  • _id can be a field path ("$region"), null, a constant, or an expression object.
  • spec accepts the standard accumulator set.

Common accumulators:

  • $sum, $avg, $min, $max, $count
  • $first, $last
  • $push, $addToSet

Advanced accumulators:

  • $top, $topN, $bottom, $bottomN
  • $percentile, $median
  • $stdDevPop, $stdDevSamp
  • $minN, $maxN, $firstN, $lastN
  • $concatArrays, $mergeObjects

project(spec)

Reshapes the document according to spec. Mongster distinguishes between inclusion keys (1), exclusion keys (0), and computed fields (anything else). Computed fields use $$field references to other document paths.

import {  } from "./models";

const  = await .()
  .({ : "us-east" })
  .({
    : 0,
    : 1,
    : { : ["$total", 100] },
  })
  .();

unwind(path, options?)

path must be a $$fieldPath literal. Pass options.preserveNullAndEmptyArrays and/or options.includeArrayIndex when needed.

lookup({ from, localField, foreignField, as })

from must be a Mongster model instance (not a collection name string). as is the output field name; you usually pair lookup with unwind to get a single joined document shape.

import { ,  } from "./models";

const  = await .()
  .({
    : ,
    : "authorId",
    : "_id",
    : "author",
  })
  .("$author")
  .();

addFields(fields)

Like project, but preserves existing fields and adds new ones. The argument is a record of field names to expressions.

import {  } from "./models";

const  = await .()
  .({ : { : ["$quantity", "$unitPrice"] } })
  .();

count(name?)

Shortcut for { $count: name }. Defaults to "count".

import {  } from "./models";

const  = await .().({ : true }).("done").();
// result: { done: number }[]

raw<ReturnType>(stage)

Use this when the typed builder cannot model a stage. You take responsibility for the shape, including the return type parameter.

import {  } from "./models";

type  = { : string; : number };
const  = await .()
  .({ : "click" })
  .<>({
    : {
      : "$kind",
      : [0, 1, 2],
      : "other",
      : { : { : 1 } },
    },
  })
  .();

Execution

MethodReturnsNotes
exec()Promise<Doc[]>Runs the cursor and returns all results.
.then / .catchthenableLets you await q directly. Call .exec() first if you need .finally().
explain()Promise<Document>Returns the MongoDB explain output without running the cursor.

On this page