agg

package
v1.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agg parses and runs the aggregation pipeline (plan §10.2, §11.3). It has no storage: the caller feeds it the matching documents (or their column values) and finishes with the pipeline stages that follow the group.

Shape

A pipeline has exactly one $group. Before it only $match and one $sort are allowed; after it $match, $sort, $limit, $skip and $project. All the $match stages before the group are ANDed into one where, which the collection plans like a find (index, pruning, snapshot). A $sort before the group only sets the order of $first and $last; it is ignored when the group has neither.

Values

A field path ("$a.b") has one value per document:

  • the value itself, when no array is on the way;
  • an array of the values (one level flattened), when the path ends in an array or walks through one ("$items.sku"). The array is one value: a group key, or a number for nothing. An empty array is an empty array.
  • missing, when the path does not exist.

The collection time field holds RFC 3339 strings as time values, so two offsets of one instant are one group key.

Group keys

_id is a path, a constant, null, a $dateTrunc, or an object of those (a composite key). Missing and null are the same key (null): a group never has two null keys. Keys follow the cross-type order of package query (number < string < time < object < array < bool, null first); a composite key compares field by field, in the order the fields were written. Groups leave the table sorted by _id, so a pipeline with no $sort is deterministic and a cursor can resume it.

Accumulators

$count        the number of documents; its argument is {}.
$sum          the sum of the numbers. Non-numbers (missing, null,
              strings, arrays) are ignored. No number gives 0.
$avg          sum / count of the numbers. No number gives null.
$min, $max    the lowest / highest value in the cross-type order. Missing
              and null are ignored; nothing left gives null. So
              $max of [2, "x"] is "x".
$first,$last  the value of the first / last document of the group, with
              missing as null. Order: the $sort before the group when
              there is one (ties: document id), else insertion order.

Sums are float64. Partial tables merge in segment order, so a sum of non-integers can differ from a sequential sum in the last bits.

$dateTrunc

{"$dateTrunc": {"date": "$ts", "unit": "hour", "timezone": "Europe/Rome"}} cuts a time down to minute, hour, day, week (Monday) or month, in the time zone (default UTC). The result is the start of the bucket as an RFC 3339 string in UTC. A value that is not a time (missing, null, a number, a string that is not RFC 3339 or YYYY-MM-DD) gives null.

Pagination

limit and skip cut the output of the last stage. after is the token of the previous page: the position in the final output, bound to the pipeline text. The pipeline runs again for each page, so rows can move between pages when data changes between requests (as plan §10.6 says for offset).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValueOf

func ValueOf(m map[string]any, path string, isTime bool) query.Value

ValueOf is the value of path in a decoded document (see the package notes).

Types

type Budget

type Budget struct {
	// contains filtered or unexported fields
}

Budget is the memory a query may use for group tables, shared by all the partial tables of the query. A limit of 0 or less is no limit.

func NewBudget

func NewBudget(limit int64) *Budget

type Find added in v1.13.2

type Find struct {
	Limit   int
	Skip    int
	After   string
	Count   bool
	Explain bool
	// contains filtered or unexported fields
}

Find is a pipeline with no $group, as MongoDB allows: it reads documents, so it runs as a find. The stages are $match, $sort, $skip, $limit and $project, in an order that a find can give:

$match and one $sort (in any order), then $skip and $limit, then one
$project (it can also come before $skip and $limit).

A $match or a $sort after $skip, $limit or $project changes the result in MongoDB, so it is invalid_pipeline here.

func ParseFind added in v1.13.2

func ParseFind(body []byte) (f *Find, ok bool, err error)

ParseFind reads an aggregate body. ok is false when the pipeline has a $group (or cannot be read): then Parse handles it. Every error has the code invalid_pipeline.

func (*Find) Page added in v1.13.2

func (f *Find) Page() (*FindPage, error)

Page makes the find body of the page that the request asks for.

type FindPage added in v1.13.2

type FindPage struct {
	Body []byte
	// contains filtered or unexported fields
}

FindPage is one page of a Find: the find body to run, and what Finish needs to give the rows, the cursor and the total of the pipeline.

func (*FindPage) Finish added in v1.13.2

func (pg *FindPage) Finish(rows []json.RawMessage, next string, total *int) ([]json.RawMessage, string, *int, error)

Finish turns the answer of the find into the answer of the pipeline.

type Options

type Options struct {
	// TimeField is the collection time field: RFC 3339 strings compare as time.
	TimeField string

	// ExpiresField is the TTL field of the collection (plan §11.5).
	ExpiresField string

	// Field is the query hook of $match (see query.Options.Field).
	Field func(path string, v any) (string, any, error)
}

Options are the collection facts the parser needs.

type Pipeline

type Pipeline struct {
	// Query is the where of the leading $match stages, plus the $sort that
	// orders $first and $last. It is never nil. The collection plans it
	// like a find.
	Query *query.Query

	Limit   int
	Skip    int
	After   string
	Count   bool
	Explain bool
	// contains filtered or unexported fields
}

Pipeline is a validated aggregate request.

func Parse

func Parse(body []byte, opts Options) (*Pipeline, error)

Parse validates the body of POST /{coll}/_aggregate. Every error has the code invalid_pipeline.

func (*Pipeline) CheckCursor

func (p *Pipeline) CheckCursor() error

CheckCursor validates After, so a bad token fails before the pipeline runs.

func (*Pipeline) Expand added in v1.20.0

func (p *Pipeline) Expand(m map[string]any, add func(vals []query.Value, elem int) error) error

Expand calls add with the group values of each row that the $unwind makes of the decoded document m, and the place of the row in the document. m is not changed.

func (*Pipeline) Finish

func (p *Pipeline) Finish(rows []map[string]any) (Result, error)

Finish runs the stages after the group on the rows of the group table and cuts the page (skip, limit, after).

func (*Pipeline) FinishTable added in v1.13.0

func (p *Pipeline) FinishTable(t *Table) (Result, error)

FinishTable is Finish on the rows of t. When the group stage is followed by $sort and $limit (the top n of a dashboard), only the first n groups become rows.

func (*Pipeline) IsTime

func (p *Pipeline) IsTime(path string) bool

IsTime tells if path is the collection time field.

func (*Pipeline) NeedsPos added in v1.13.0

func (p *Pipeline) NeedsPos() bool

NeedsPos tells whether the group stage keeps an order ($first, $last): only then does each row need its position (its id and sort keys).

func (*Pipeline) NewTable

func (p *Pipeline) NewTable(budget *Budget) *Table

NewTable makes an empty table that charges its groups to budget.

func (*Pipeline) Paths

func (p *Pipeline) Paths() []string

Paths lists the document paths the group reads, in the order that Values returns them. The where and sort paths are read through Query.

func (*Pipeline) UnwindPaths added in v1.20.0

func (p *Pipeline) UnwindPaths() []string

UnwindPaths are the document paths that Expand reads besides Paths: the array, and the fields of the $match after the $unwind.

func (*Pipeline) Unwound added in v1.20.0

func (p *Pipeline) Unwound() bool

Unwound tells if the pipeline has an $unwind: then the group reads rows of Expand, not documents.

func (*Pipeline) Values

func (p *Pipeline) Values(m map[string]any) []query.Value

Values reads the group paths of a decoded document.

type Result

type Result struct {
	Rows []json.RawMessage

	// Next is the cursor for the following page; empty on the last page.
	Next string

	// Total is the number of rows of the last stage, before limit and skip.
	Total int
}

Result is the final page of an aggregate.

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table is a group table: the partial result of one segment or of the memtable. Tables of one query merge into one. A table is for one goroutine.

func (*Table) Add

func (t *Table) Add(vals []query.Value, pos query.Pos) error

Add counts one document in its group. vals are the values of Paths, and pos is the position of the document, which $first and $last use. Add keeps no reference to vals.

func (*Table) AddElem added in v1.20.0

func (t *Table) AddElem(vals []query.Value, pos query.Pos, elem int) error

AddElem is Add for one row of an $unwind: elem is the place of the element in its document.

func (*Table) Len

func (t *Table) Len() int

Len is the number of groups.

func (*Table) Merge

func (t *Table) Merge(o *Table) error

Merge adds the groups of o into t. o is not used after.

func (*Table) Rows

func (t *Table) Rows() []map[string]any

Rows are the output rows of the group stage, sorted by _id.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL