Menu
#Aggregation
aggregate runs a pipeline over a collection and replies with docs.
{"cmd":"aggregate","collection":"users","pipeline":[{"$match":{"age":{"$gte":18}}},{"$group":{"_id":"$address.city","people":{"$sum":1},"oldest":{"$max":"$age"}}},{"$sort":{"people":-1}}]}{"docs":[{"_id":"Leeds","oldest":26,"people":1},{"_id":"York","oldest":31,"people":1}],"ok":true}The reply is cut off at the same size as find. It needs the read role, unless the pipeline ends in $out or $merge. A pipeline has at most 100 stages, each stage is checked when the request is parsed, and an error names the stage.
#How it runs
- A leading
$match, followed by an optional$sort,$skipand$limitin that order, is run as afind, so indexes, early stop and sorts through an index are used. Put$matchfirst, and$sortand$limitbefore$project, or$projectcopies every document first. $match,$skip,$limit,$project,$addFields,$unset,$unwind,$lookupand$replaceRootstream documents.$sort,$group,$count,$sortByCountand the bucket stages have to hold them.- A stage that has to hold documents holds at most 100 MiB. One expression or document it builds is capped at 16 MiB. Going over is a
limiterror. - A stage that reads another collection (
$lookup,$graphLookup,$facetwith one of them) copies what came before it (at most 100 MiB, else an error that says to match or limit earlier) and lets go of the first collection's lock. A request never holds two collection locks. - A collection that does not exist is empty.
#Stages
| Stage | Does |
|---|---|
$match |
filters. Takes a filter, and $expr at the top level |
$project |
includes, excludes or computes fields |
$addFields, $set |
adds or replaces fields |
$unset |
removes fields |
$sort |
sorts |
$skip, $limit |
passes over or keeps the first documents |
$count |
counts the documents into one field |
$group |
groups and accumulates |
$sortByCount |
groups by an expression and sorts by count |
$unwind |
one document for each array element |
$lookup |
joins another collection |
$graphLookup |
follows links through another collection |
$facet |
several pipelines over the same input |
$bucket, $bucketAuto |
groups into ranges |
$replaceRoot, $replaceWith |
makes a field the whole document |
$out, $merge |
writes the result to a collection |
#$match
{"$match":{"age":{"$gte":18},"$expr":{"$gt":["$price",{"$multiply":["$cost",2]}]}}}$expr compares fields of the same document with expression operators. A $match with $expr is not turned into an index lookup.
#$project
Either flags, as in a find projection (1, 0, true, false), or expressions that compute fields:
{"$project":{"cust":1,"who":"$c.name","total":{"$multiply":["$qty","$price"]},"_id":0}}You cannot leave fields out and compute fields in one $project, except for _id. A computed field whose expression finds nothing is left out of the result.
#$addFields and $set
{"$addFields":{"big":{"$cond":[{"$gt":["$price",6]},"y","n"]}}}Every expression reads the document as it came in. A nested document replaces the field, where MongoDB merges it.
#$unset
A path, or a list of paths: {"$unset":"_id"} or {"$unset":["a","b.c"]}.
#$sort, $skip, $limit
$sort is {"age":-1} for one field and [["age",-1],["name",1]] for several, as in find. $skip takes a whole number, 0 or more. $limit takes one of at least 1. A $sort followed by $limit only sorts the first n.
#$count
{"$count":"n"} gives one document {"n":<count>}. When there are no documents it gives none. The name cannot be empty, contain a . or start with $.
#$group
{"$group":{"_id":"$cust","total":{"$sum":"$price"},"n":{"$count":{}}}}_id is required. It is null to put everything in one group, a path, an expression, or a document of expressions. Each other field takes one accumulator:
| Accumulator | Gives |
|---|---|
$sum |
the total of the numbers. Values that are not numbers are ignored |
$avg |
the mean of the numbers, or null when there were none |
$min, $max |
the lowest or highest in sort order. Nulls and missing fields are ignored |
$first, $last |
the first or last value met |
$push |
an array of the values |
$addToSet |
an array of the distinct values |
$count |
the number of documents. Takes {} |
Groups are keyed on a canonical encoding, so 1 and 1.0 share a group and the order of fields in a document does not matter. Groups come out in the order they were first met, so sort afterwards if the order matters.
#$sortByCount
{"$sortByCount":"$cust"} is a $group by that expression with a count, sorted by count, highest first. Each result is {"_id":...,"count":n}.
#$unwind
A path, or a document:
{"$unwind":"$items"}{"$unwind":{"path":"$items","preserveNullAndEmptyArrays":true,"includeArrayIndex":"i"}}| Option | Meaning |
|---|---|
path |
the array field, as "$a.b" |
preserveNullAndEmptyArrays |
keep documents whose field is null, missing or an empty array |
includeArrayIndex |
a field to put the element's position in |
A field that is not an array is treated as an array of one.
#$lookup
The simple form joins on equal fields:
{"$lookup":{"from":"custs","localField":"cust","foreignField":"cid","as":"c"}}Each document gets as, an array of the matching documents from from. It is quick with an index on foreignField (or on _id), and without one the first 8 documents scan and then a hash table is built.
The second form takes a pipeline, and let to give it values from the outer document as $$name:
{"$lookup":{"from":"orders","let":{"c":"$cid"},"pipeline":[{"$match":{"$expr":{"$eq":["$cust","$$c"]}}},{"$project":{"price":1,"_id":0}}],"as":"o"}}- Only
from,as,letandpipelineare accepted in this form, solocalFieldandforeignFieldcannot be mixed with it. - A variable name is a lower case letter, then letters, digits and
_. It is read only where a stage takes an expression, such as$expr,$projector$addFields. In the filter of a$match, a field name, a collection name or a sort key,$$cis just text. - The pipeline is parsed again for each outer document, and its result for one document is at most 16 MiB.
$outand$mergecannot be inside it.
#$graphLookup
{"$graphLookup":{"from":"staff","startWith":"$boss","connectFromField":"boss","connectToField":"name","as":"chain","maxDepth":3,"depthField":"level"}}| Option | Meaning |
|---|---|
from, as |
the collection to search, and the array field for the result |
startWith |
an expression for the first value or values to look for |
connectFromField |
the field of each found document that holds the next values to look for |
connectToField |
the field those values are looked up in |
maxDepth |
the most levels to go, 0 to 100. Without it, the search goes until nothing new is found, and over 100 levels is a limit error |
depthField |
a field to put each found document's level in, starting at 0 |
restrictSearchWithMatch |
a filter every found document has to meet |
Each document is found once. Every level is a search of the other collection, so an index on connectToField helps.
#$facet
Several pipelines over the same input, each giving an array in one result document:
{"$facet":{"n":[{"$count":"n"}],"by":[{"$group":{"_id":"$cust","t":{"$sum":"$price"}}}]}}The reply is one document with the fields n and by. A branch cannot hold $out, $merge or another $facet. The output is one document, so it is at most 16 MiB, and the input it holds is at most 100 MiB.
#$bucket
{"$bucket":{"groupBy":"$price","boundaries":[0,10,20],"default":"other","output":{"n":{"$sum":1}}}}| Option | Meaning |
|---|---|
groupBy |
an expression |
boundaries |
at least two values of one type, ascending. A bucket is [boundary, next boundary) and its _id is the lower boundary |
default |
the _id of the bucket for values outside the boundaries, which has to be outside them. Without it, a value outside is an error |
output |
accumulators, as in $group (without _id). Defaults to {"count":{"$sum":1}} |
#$bucketAuto
{"$bucketAuto":{"groupBy":"$price","buckets":2}}Sorts by the value and cuts it into buckets groups of about the same size, keeping equal values together. Each _id is {"min":...,"max":...}. output is as for $bucket. granularity is not supported.
#$replaceRoot and $replaceWith
{"$replaceRoot":{"newRoot":"$address"}}{"$replaceWith":{"c":"$cust","b":"$big"}}The expression has to give a document, else it is an error.
#$out
{"$out":"totals"}Replaces the target collection with the result. The target is a collection name, or {"db":"other","coll":"totals"}. It has to be the last stage, and it cannot be inside $lookup or $facet. The user needs readWrite on the target and on its database.
_id has to be an ObjectId or absent, so after a $group use {"$unset":"_id"} before $out to get new ids. The collection keeps its indexes. The reply is {"docs":[],"count":n}, and the write goes into the log as one record, all or nothing. The output is at most 100 MiB.
#$merge
{"$merge":{"into":"totals","on":"_id","whenMatched":"replace","whenNotMatched":"insert"}}| Option | Meaning |
|---|---|
into |
a collection name or {"db","coll"}. A bare name works as the whole spec |
on |
a field or a list of fields that match documents. Default _id. Anything else needs a unique index on exactly those fields |
whenMatched |
replace, merge (the default), keepExisting or fail. A pipeline here is not supported |
whenNotMatched |
insert (the default), discard or fail |
With on as _id, every document has to have an _id, so a $project that drops it will fail. The same placement rules and permissions as $out apply, and the write is one log record. The reply is {"docs":[],"count":n}.
Neither $out nor $merge is allowed inside a transaction, and a follower refuses them.
#Expressions
An expression is a field path ("$address.city"), a literal, an object or array of expressions, or an operator document with exactly one operator.
"$$ROOT"and"$$CURRENT"are the whole document. They are the only built-in variables.{"$literal":value}is the value as it is, even if it looks like a path or an operator.- A missing field is null as an operand, but a stage leaves a missing computed field out of the document it builds.
- Field names in an object expression cannot be empty or contain a
..
| Operator | Arguments | Gives |
|---|---|---|
$add |
1 or more | the sum. A date plus a number is a date |
$subtract |
2 | the difference. A date minus a date is a number, a date minus a number is a date |
$multiply |
1 or more | the product |
$divide |
2 | the quotient, always a float. Dividing by zero is an error |
$mod |
2 | the remainder, which takes the sign of the first. A zero divisor is an error |
$abs, $floor, $ceil |
1 | the absolute value, rounded down, rounded up |
$round |
1 or 2 | rounded to a number of places from -20 to 100, default 0. Halves round to even |
$concat |
1 or more | the strings joined. Any null or missing gives null |
$toUpper, $toLower |
1 | the string in that case. Null gives an empty string |
$strLenCP |
1 | the length in code points |
$substrCP |
3 | a substring: string, start, length. A length of -1 or more than is left means the rest |
$size |
1 | the length of an array. Anything else is an error |
$arrayElemAt |
2 | the element at an index. A negative index counts from the end |
$isArray |
1 | whether it is an array |
$in |
2 | whether a value is in an array |
$ifNull |
2 or more | the first argument that is not null or missing |
$cond |
3 | [if, then, else] or {"if":..,"then":..,"else":..}. Only the branch taken is run |
$eq, $ne, $gt, $gte, $lt, $lte |
2 | a comparison, in sort order across types, so a string is above a number |
$and, $or |
any number | a boolean. They stop as soon as the answer is known |
$not |
1 | the opposite of a boolean |
$type |
1 | the type name: null, bool, int, double, string, objectId, date, regex, array, object or missing |
Whole numbers stay whole in $add, $subtract, $multiply, $sum, $abs, $floor, $ceil and $round, and become floats if they would overflow. A result that is not finite is an invalid error. $and, $or, $not and $cond treat null, missing, false and 0 as false, and anything else as true.
An operator with a single argument can be written without the array: {"$toUpper":"$name"}.
#Not supported
$map, $reduce, granularity in $bucketAuto, a pipeline in $merge's whenMatched, $facet inside $facet, and every stage and expression operator not listed above. Asking for one gives an invalid error that names it.