Docs HomeMongoDB Manual

Aggregation Pipeline Quick Reference

Note

For details on a specific operator, including syntax and examples, click on the link to the operator's reference page.

Stages

Stages (db.collection.aggregate)

In the db.collection.aggregate() method, pipeline stages appear in an array. Documents pass through the stages in sequence. All except the $out, $merge, and $geoNear stages can appear multiple times in a pipeline.

db.collection.aggregate( [ { <stage> }, ... ] )
StageDescription描述
$addFieldsAdds new fields to documents. Similar to $project, $addFields reshapes each document in the stream; specifically, by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields.
$set is an alias for $addFields.
$bucketCategorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.
$bucketAutoCategorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets.
$changeStreamReturns a Change Stream cursor for the collection. This stage can only occur once in an aggregation pipeline and it must occur as the first stage.
$collStatsReturns statistics regarding a collection or view.
$countReturns a count of the number of documents at this stage of the aggregation pipeline.
Distinct from the $count aggregation accumulator.
$densifyCreates new documents in a sequence of documents where certain values in a field are missing.
$documentsReturns literal documents from input expressions.
$facetProcesses multiple aggregation pipelines within a single stage on the same set of input documents. Enables the creation of multi-faceted aggregations capable of characterizing data across multiple dimensions, or facets, in a single stage.
$fillPopulates null and missing field values within documents.
$geoNearReturns an ordered stream of documents based on the proximity to a geospatial point. Incorporates the functionality of $match, $sort, and $limit for geospatial data. The output documents include an additional distance field and can include a location identifier field.
$graphLookupPerforms a recursive search on a collection. To each output document, adds a new array field that contains the traversal results of the recursive search for that document.
$groupGroups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. Consumes all input documents and outputs one document per each distinct group. The output documents only contain the identifier field and, if specified, accumulated fields.
$indexStatsReturns statistics regarding the use of each index for the collection.
$limitPasses the first n documents unmodified to the pipeline where n is the specified limit. For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents).
$listSessionsLists all sessions that have been active long enough to propagate to the system.sessions collection.
$lookupPerforms a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing.
$matchFilters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. $match uses standard MongoDB queries. For each input document, outputs either one document (a match) or zero documents (no match).
$mergeWrites the resulting documents of the aggregation pipeline to a collection. The stage can incorporate (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) the results into an output collection. To use the $merge stage, it must be the last stage in the pipeline.
New in version 4.2.
$outWrites the resulting documents of the aggregation pipeline to a collection. To use the $out stage, it must be the last stage in the pipeline.
$planCacheStatsReturns plan cache information for a collection.
$projectReshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document.
See also $unset for removing existing fields.
$redactReshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. Incorporates the functionality of $project and $match. Can be used to implement field level redaction. For each input document, outputs either one or zero documents.
$replaceRootReplaces a document with the specified embedded document. The operation replaces all existing fields in the input document, including the _id field. Specify a document embedded in the input document to promote the embedded document to the top level.
$replaceWith is an alias for $replaceRoot stage.
$replaceWithReplaces a document with the specified embedded document. The operation replaces all existing fields in the input document, including the _id field. Specify a document embedded in the input document to promote the embedded document to the top level.
$replaceWith is an alias for $replaceRoot stage.
$sampleRandomly selects the specified number of documents from its input.
$searchPerforms a full-text search of the field or fields in an Atlas collection.
Note
$search is only available for MongoDB Atlas clusters, and is not available for self-managed deployments. To learn more, see Atlas Search Aggregation Pipeline Stages.
$searchMetaReturns different types of metadata result documents for the Atlas Search query against an Atlas collection.
Note
$searchMeta is only available for MongoDB Atlas clusters running MongoDB v4.4.9 or higher, and is not available for self-managed deployments. To learn more, see Atlas Search Aggregation Pipeline Stages.
$setAdds new fields to documents. Similar to $project, $set reshapes each document in the stream; specifically, by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields.
$set is an alias for $addFields stage.
$setWindowFieldsGroups documents into windows and applies one or more operators to the documents in each window.
New in version 5.0.
$skipSkips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents).
$sortReorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document.
$sortByCountGroups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
$unionWithPerforms a union of two collections; i.e. combines pipeline results from two collections into a single result set.
New in version 4.4.
$unsetRemoves/excludes fields from documents.
$unset is an alias for $project stage that removes fields.
$unwindDeconstructs an array field from the input documents to output a document for each element. Each output document replaces the array with an element value. For each input document, outputs n documents where n is the number of array elements and can be zero for an empty array.

Stages (db.aggregate)

Starting in version 3.6, MongoDB also provides the db.aggregate() method:

db.aggregate( [ { <stage> }, ... ] )

The following stages use the db.aggregate() method and not the db.collection.aggregate() method.

StageDescription描述
$changeStreamReturns a Change Stream cursor for the collection. This stage can only occur once in an aggregation pipeline and it must occur as the first stage.
$currentOpReturns information on active and/or dormant operations for the MongoDB deployment.
$listLocalSessionsLists all active sessions recently in use on the currently connected mongos or mongod instance. These sessions may have not yet propagated to the system.sessions collection.
$documentsReturns literal documents from input values.

Stages Available for Updates

Starting in MongoDB 4.2, you can use the aggregation pipeline for updates in:

Commandmongosh Methods
findAndModifydb.collection.findOneAndUpdate()
db.collection.findAndModify()
updatedb.collection.updateOne()
db.collection.updateMany()
Bulk.find.update()
Bulk.find.updateOne()
Bulk.find.upsert()

For the updates, the pipeline can consist of the following stages:

Tip

See also: 另请参阅:

Updates with Aggregation Pipeline

Expressions

Expressions can include field paths, literals, system variables, expression objects, and expression operators. Expressions can be nested.

Field Paths

Aggregation expressions use field path to access fields in the input documents. To specify a field path, prefix the field name or the dotted field name (if the field is in the embedded document) with a dollar sign $. For example, "$user" to specify the field path for the user field or "$user.name" to specify the field path to "user.name" field.

"$<field>" is equivalent to "$$CURRENT.<field>" where the CURRENT is a system variable that defaults to the root of the current object, unless stated otherwise in specific stages.

Aggregation Variables

MongoDB provides various aggregation system variables for use in expressions. To access variables, prefix the variable name with $$. For example:例如:

VariableAccess via $$Brief Description
NOW$$NOWReturns the current datetime value, which is same across all members of the deployment and remains constant throughout the aggregation pipeline. (Available in 4.2+)
CLUSTER_TIME$$CLUSTER_TIMEReturns the current timestamp value, which is same across all members of the deployment and remains constant throughout the aggregation pipeline. For replica sets and sharded clusters only. (Available in 4.2+)
ROOT$$ROOTReferences the root document, i.e. the top-level document.
CURRENT$$CURRENTReferences the start of the field path, which by default is ROOT but can be changed.
REMOVE$$REMOVEAllows for the conditional exclusion of fields. (Available in 3.6+)
DESCEND$$DESCENDOne of the allowed results of a $redact expression.
PRUNE$$PRUNEOne of the allowed results of a $redact expression.
KEEP$$KEEPOne of the allowed results of a $redact expression.

For a more detailed description of these variables, see system variables.

Literals

Literals can be of any type. However, MongoDB parses string literals that start with a dollar sign $ as a path to a field and numeric/boolean literals in expression objects as projection flags. To avoid parsing literals, use the $literal expression.

Expression Objects

Expression objects have the following form:

{ <field1>: <expression1>, ... }

If the expressions are numeric or boolean literals, MongoDB treats the literals as projection flags (e.g. 1 or true to include the field), valid only in the $project stage. To avoid treating numeric or boolean literals as projection flags, use the $literal expression to wrap the numeric or boolean literals.

Operator Expressions

Operator expressions are similar to functions that take arguments. In general, these expressions take an array of arguments and have the following form:

{ <operator>: [ <argument1>, <argument2> ... ] }

If operator accepts a single argument, you can omit the outer array designating the argument list:

{ <operator>: <argument> }

To avoid parsing ambiguity if the argument is a literal array, you must wrap the literal array in a $literal expression or keep the outer array that designates the argument list.

Arithmetic Expression Operators

Arithmetic expressions perform mathematic operations on numbers. Some arithmetic expressions can also support date arithmetic.

Name名称Description描述
$absReturns the absolute value of a number.
$addAdds numbers to return the sum, or adds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date.
$ceilReturns the smallest integer greater than or equal to the specified number.
$divideReturns the result of dividing the first number by the second. Accepts two argument expressions.
$expRaises e to the specified exponent.
$floorReturns the largest integer less than or equal to the specified number.
$lnCalculates the natural log of a number.
$logCalculates the log of a number in the specified base.
$log10Calculates the log base 10 of a number.
$modReturns the remainder of the first number divided by the second. Accepts two argument expressions.
$multiplyMultiplies numbers to return the product. Accepts any number of argument expressions.
$powRaises a number to the specified exponent.
$roundRounds a number to to a whole integer or to a specified decimal place.
$sqrtCalculates the square root.
$subtractReturns the result of subtracting the second value from the first. If the two values are numbers, return the difference. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number.
$truncTruncates a number to a whole integer or to a specified decimal place.

Array Expression Operators

Name名称Description描述
$arrayElemAtReturns the element at the specified array index.
$arrayToObjectConverts an array of key value pairs to a document.
$concatArraysConcatenates arrays to return the concatenated array.
$filterSelects a subset of the array to return an array with only the elements that match the filter condition.
$firstNReturns a specified number of elements from the beginning of an array. Distinct from the $firstN accumulator.
$inReturns a boolean indicating whether a specified value is in an array.
$indexOfArraySearches an array for an occurrence of a specified value and returns the array index of the first occurrence. If the substring is not found, returns -1.
$isArrayDetermines if the operand is an array. Returns a boolean.
$lastNReturns a specified number of elements from the end of an array. Distinct from the $lastN accumulator.
$mapApplies a subexpression to each element of an array and returns the array of resulting values in order. Accepts named parameters.
$maxNReturns the n largest values in an array. Distinct from the $maxN accumulator.
$minNReturns the n smallest values in an array. Distinct from the $minN accumulator.
$objectToArrayConverts a document to an array of documents representing key-value pairs.
$rangeOutputs an array containing a sequence of integers according to user-defined inputs.
$reduceApplies an expression to each element in an array and combines them into a single value.
$reverseArrayReturns an array with the elements in reverse order.
$sizeReturns the number of elements in the array. Accepts a single expression as argument.
$sliceReturns a subset of an array.
$sortArraySorts the elements of an array.
$zipMerge two arrays together.

Boolean Expression Operators

Boolean expressions evaluate their argument expressions as booleans and return a boolean as the result.

In addition to the false boolean value, Boolean expression evaluates as false the following: null, 0, and undefined values. The Boolean expression evaluates all other values as true, including non-zero numeric values and arrays.

Name名称Description描述
$andReturns true only when all its expressions evaluate to true. Accepts any number of argument expressions.
$notReturns the boolean value that is the opposite of its argument expression. Accepts a single argument expression.
$orReturns true when any of its expressions evaluates to true. Accepts any number of argument expressions.

Comparison Expression Operators

Comparison expressions return a boolean except for $cmp which returns a number.

The comparison expressions take two argument expressions and compare both value and type, using the specified BSON comparison order for values of different types.

Name名称Description描述
$cmpReturns 0 if the two values are equivalent, 1 if the first value is greater than the second, and -1 if the first value is less than the second.
$eqReturns true if the values are equivalent.
$gtReturns true if the first value is greater than the second.
$gteReturns true if the first value is greater than or equal to the second.
$ltReturns true if the first value is less than the second.
$lteReturns true if the first value is less than or equal to the second.
$neReturns true if the values are not equivalent.

Conditional Expression Operators

Name名称Description描述
$condA ternary operator that evaluates one expression, and depending on the result, returns the value of one of the other two expressions. Accepts either three expressions in an ordered list or three named parameters.
$ifNullReturns either the non-null result of the first expression or the result of the second expression if the first expression results in a null result. Null result encompasses instances of undefined values or missing fields. Accepts two expressions as arguments. The result of the second expression can be null.
$switchEvaluates a series of case expressions. When it finds an expression which evaluates to true, $switch executes a specified expression and breaks out of the control flow.

Custom Aggregation Expression Operators自定义聚合表达式运算符

Name名称Description描述
$accumulatorDefines a custom accumulator function.
New in version 4.4.
$functionDefines a custom function.
New in version 4.4.

Data Size Expression Operators

The following operators return the size of a data element:

Name名称Description描述
$binarySizeReturns the size of a given string or binary data value's content in bytes.返回给定字符串或二进制数据值内容的大小(以字节为单位)。
$bsonSizeReturns the size in bytes of a given document (i.e. bsontype Object) when encoded as BSON.

Date Expression Operators

The following operators returns date objects or components of a date object:

Name名称Description描述
$dateAddAdds a number of time units to a date object.
$dateDiffReturns the difference between two dates.
$dateFromPartsConstructs a BSON Date object given the date's constituent parts.
$dateFromStringConverts a date/time string to a date object.
$dateSubtractSubtracts a number of time units from a date object.
$dateToPartsReturns a document containing the constituent parts of a date.
$dateToStringReturns the date as a formatted string.
$dateTruncTruncates a date.
$dayOfMonthReturns the day of the month for a date as a number between 1 and 31.
$dayOfWeekReturns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday).
$dayOfYearReturns the day of the year for a date as a number between 1 and 366 (leap year).
$hourReturns the hour for a date as a number between 0 and 23.
$isoDayOfWeekReturns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday).
$isoWeekReturns the week number in ISO 8601 format, ranging from 1 to 53. Week numbers start at 1 with the week (Monday through Sunday) that contains the year's first Thursday.
$isoWeekYearReturns the year number in ISO 8601 format. The year starts with the Monday of week 1 (ISO 8601) and ends with the Sunday of the last week (ISO 8601).
$millisecondReturns the milliseconds of a date as a number between 0 and 999.
$minuteReturns the minute for a date as a number between 0 and 59.
$monthReturns the month for a date as a number between 1 (January) and 12 (December).
$secondReturns the seconds for a date as a number between 0 and 60 (leap seconds).
$toDateConverts value to a Date.
New in version 4.0.
$weekReturns the week number for a date as a number between 0 (the partial week that precedes the first Sunday of the year) and 53 (leap year).
$yearReturns the year for a date as a number (e.g. 2014).

The following arithmetic operators can take date operands:

Name名称Description描述
$addAdds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date.
$subtractReturns the result of subtracting the second value from the first. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number.

Literal Expression Operator

Name名称Description描述
$literalReturn a value without parsing. Use for values that the aggregation pipeline may interpret as an expression. For example, use a $literal expression to a string that starts with a dollar sign ($) to avoid parsing as a field path.

Miscellaneous Operators

Name名称Description描述
$getFieldReturns the value of a specified field from a document. You can use $getField to retrieve the value of fields with names that contain periods (.) or start with dollar signs ($).
New in version 5.0.
$randReturns a random float between 0 and 1
$sampleRateRandomly select documents at a given rate. Although the exact number of documents selected varies on each run, the quantity chosen approximates the sample rate expressed as a percentage of the total number of documents.

Object Expression Operators

Name名称Description描述
$mergeObjectsCombines multiple documents into a single document.
$objectToArrayConverts a document to an array of documents representing key-value pairs.
$setFieldAdds, updates, or removes a specified field in a document. You can use $setField to add, update, or remove fields with names that contain periods (.) or start with dollar signs ($).
New in version 5.0.

Set Expression Operators

Set expressions performs set operation on arrays, treating arrays as sets. Set expressions ignores the duplicate entries in each input array and the order of the elements.

If the set operation returns a set, the operation filters out duplicates in the result to output an array that contains only unique entries. The order of the elements in the output array is unspecified.

If a set contains a nested array element, the set expression does not descend into the nested array but evaluates the array at top-level.

Name名称Description描述
$allElementsTrueReturns true if no element of a set evaluates to false, otherwise, returns false. Accepts a single argument expression.
$anyElementTrueReturns true if any elements of a set evaluate to true; otherwise, returns false. Accepts a single argument expression.
$setDifferenceReturns a set with elements that appear in the first set but not in the second set; i.e. performs a relative complement of the second set relative to the first. Accepts exactly two argument expressions.
$setEqualsReturns true if the input sets have the same distinct elements. Accepts two or more argument expressions.
$setIntersectionReturns a set with elements that appear in all of the input sets. Accepts any number of argument expressions.
$setIsSubsetReturns true if all elements of the first set appear in the second set, including when the first set equals the second set; i.e. not a strict subset. Accepts exactly two argument expressions.
$setUnionReturns a set with elements that appear in any of the input sets.

String Expression Operators

String expressions, with the exception of $concat, only have a well-defined behavior for strings of ASCII characters.

$concat behavior is well-defined regardless of the characters used.

Name名称Description描述
$concatConcatenates any number of strings.
$dateFromStringConverts a date/time string to a date object.
$dateToStringReturns the date as a formatted string.
$indexOfBytesSearches a string for an occurrence of a substring and returns the UTF-8 byte index of the first occurrence. If the substring is not found, returns -1.
$indexOfCPSearches a string for an occurrence of a substring and returns the UTF-8 code point index of the first occurrence. If the substring is not found, returns -1
$ltrimRemoves whitespace or the specified characters from the beginning of a string.
New in version 4.0.
$regexFindApplies a regular expression (regex) to a string and returns information on the first matched substring.
New in version 4.2.
$regexFindAllApplies a regular expression (regex) to a string and returns information on the all matched substrings.
New in version 4.2.
$regexMatchApplies a regular expression (regex) to a string and returns a boolean that indicates if a match is found or not.
New in version 4.2.
$replaceOneReplaces the first instance of a matched string in a given input.
New in version 4.4.
$replaceAllReplaces all instances of a matched string in a given input.
New in version 4.4.
$rtrimRemoves whitespace or the specified characters from the end of a string.
New in version 4.0.
$splitSplits a string into substrings based on a delimiter. Returns an array of substrings. If the delimiter is not found within the string, returns an array containing the original string.
$strLenBytesReturns the number of UTF-8 encoded bytes in a string.
$strLenCPReturns the number of UTF-8 code points in a string.
$strcasecmpPerforms case-insensitive string comparison and returns: 0 if two strings are equivalent, 1 if the first string is greater than the second, and -1 if the first string is less than the second.
$substrDeprecated. Use $substrBytes or $substrCP.
$substrBytesReturns the substring of a string. Starts with the character at the specified UTF-8 byte index (zero-based) in the string and continues for the specified number of bytes.
$substrCPReturns the substring of a string. Starts with the character at the specified UTF-8 code point (CP) index (zero-based) in the string and continues for the number of code points specified.
$toLowerConverts a string to lowercase. Accepts a single argument expression.
$toStringConverts value to a string.
New in version 4.0.
$trimRemoves whitespace or the specified characters from the beginning and end of a string.
New in version 4.0.
$toUpperConverts a string to uppercase. Accepts a single argument expression.

Text Expression Operator

Name名称Description描述
$metaAccess available per-document metadata related to the aggregation operation.

Trigonometry Expression Operators

Trigonometry expressions perform trigonometric operations on numbers. Values that represent angles are always input or output in radians. Use $degreesToRadians and $radiansToDegrees to convert between degree and radian measurements.

Name名称Description描述
$sinReturns the sine of a value that is measured in radians.
$cosReturns the cosine of a value that is measured in radians.
$tanReturns the tangent of a value that is measured in radians.
$asinReturns the inverse sin (arc sine) of a value in radians.
$acosReturns the inverse cosine (arc cosine) of a value in radians.
$atanReturns the inverse tangent (arc tangent) of a value in radians.
$atan2Returns the inverse tangent (arc tangent) of y / x in radians, where y and x are the first and second values passed to the expression respectively.
$asinhReturns the inverse hyperbolic sine (hyperbolic arc sine) of a value in radians.
$acoshReturns the inverse hyperbolic cosine (hyperbolic arc cosine) of a value in radians.
$atanhReturns the inverse hyperbolic tangent (hyperbolic arc tangent) of a value in radians.
$sinhReturns the hyperbolic sine of a value that is measured in radians.
$coshReturns the hyperbolic cosine of a value that is measured in radians.
$tanhReturns the hyperbolic tangent of a value that is measured in radians.
$degreesToRadiansConverts a value from degrees to radians.
$radiansToDegreesConverts a value from radians to degrees.

Type Expression Operators

Name名称Description描述
$convertConverts a value to a specified type.
New in version 4.0.
$isNumberReturns boolean true if the specified expression resolves to an integer, decimal, double, or long.
Returns boolean false if the expression resolves to any other BSON type, null, or a missing field.
New in version 4.4.
$toBoolConverts value to a boolean.
New in version 4.0.
$toDateConverts value to a Date.
New in version 4.0.
$toDecimalConverts value to a Decimal128.
New in version 4.0.
$toDoubleConverts value to a double.
New in version 4.0.
$toIntConverts value to an integer.
New in version 4.0.
$toLongConverts value to a long.
New in version 4.0.
$toObjectIdConverts value to an ObjectId.
New in version 4.0.
$toStringConverts value to a string.
New in version 4.0.
$typeReturn the BSON data type of the field.

Accumulators ($group, $bucket, $bucketAuto, $setWindowFields)

Aggregation accumulator operators:

Changed in version 5.0.

Name名称Description描述
$accumulatorReturns the result of a user-defined accumulator function.
$addToSetReturns an array of unique expression values for each group. Order of the array elements is undefined.
Changed in version 5.0: Available in the $setWindowFields stage.
$avgReturns an average of numerical values. Ignores non-numeric values.
Changed in version 5.0: Available in the $setWindowFields stage.
$bottomReturns the bottom element within a group according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$bottomNReturns an aggregation of the bottom n fields within a group, according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$countReturns the number of documents in a group.
Distinct from the $count pipeline stage.
New in version 5.0: Available in the $group and $setWindowFields stages.
$firstReturns the result of an expression for the first document in a group.
Changed in version 5.0: Available in the $setWindowFields stage.
$firstNReturns an aggregation of the first n elements within a group. Only meaningful when documents are in a defined order. Distinct from the $firstN array operator.
New in version 5.2: Available in the $group, expression and $setWindowFields stages.
$lastReturns the result of an expression for the last document in a group.
Changed in version 5.0: Available in the $setWindowFields stage.
$lastNReturns an aggregation of the last n elements within a group. Only meaningful when documents are in a defined order. Distinct from the $lastN array operator.
New in version 5.2: Available in the $group, expression and $setWindowFields stages.
$maxReturns the highest expression value for each group.
Changed in version 5.0: Available in the $setWindowFields stage.
$maxNReturns an aggregation of the n maximum valued elements in a group. Distinct from the $maxN array operator.
New in version 5.2.
Available in $group, $setWindowFields and as an expression.
$mergeObjectsReturns a document created by combining the input documents for each group.
$minReturns the lowest expression value for each group.
Changed in version 5.0: Available in the $setWindowFields stage.
$pushReturns an array of expression values for documents in each group.
Changed in version 5.0: Available in the $setWindowFields stage.
$stdDevPopReturns the population standard deviation of the input values.
Changed in version 5.0: Available in the $setWindowFields stage.
$stdDevSampReturns the sample standard deviation of the input values.
Changed in version 5.0: Available in the $setWindowFields stage.
$sumReturns a sum of numerical values. Ignores non-numeric values.
Changed in version 5.0: Available in the $setWindowFields stage.
$topReturns the top element within a group according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$topNReturns an aggregation of the top n fields within a group, according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.

Accumulators (in Other Stages)

Some operators that are available as accumulators for the $group stage are also available for use in other stages but not as accumulators. When used in these other stages, these operators do not maintain their state and can take as input either a single argument or multiple arguments. For details, refer to the specific operator page.

Changed in version 5.0.

The following accumulator operators are also available in the $project, $addFields, $set, and, starting in MongoDB 5.0, the $setWindowFields stages.

Name名称Description描述
$avgReturns an average of the specified expression or list of expressions for each document. Ignores non-numeric values.
$firstReturns the result of an expression for the first document in a group.
$lastReturns the result of an expression for the last document in a group.
$maxReturns the maximum of the specified expression or list of expressions for each document
$minReturns the minimum of the specified expression or list of expressions for each document
$stdDevPopReturns the population standard deviation of the input values.
$stdDevSampReturns the sample standard deviation of the input values.
$sumReturns a sum of numerical values. Ignores non-numeric values.

Variable Expression Operators

Name名称Description描述
$letDefines variables for use within the scope of a subexpression and returns the result of the subexpression. Accepts named parameters.
Accepts any number of argument expressions.

Window Operators

New in version 5.0.

Window operators return values from a defined span of documents from a collection, known as a window. A window is defined in the $setWindowFields stage, available starting in MongoDB 5.0.

The following window operators are available in the $setWindowFields stage.

Name名称Description描述
$addToSetReturns an array of all unique values that results from applying an expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$avgReturns the average for the specified expression. Ignores non-numeric values.
Changed in version 5.0: Available in the $setWindowFields stage.
$bottomReturns the bottom element within a group according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$bottomNReturns an aggregation of the bottom n fields within a group, according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$countReturns the number of documents in the group or window.
Distinct from the $count pipeline stage.
New in version 5.0.
$covariancePopReturns the population covariance of two numeric expressions.
New in version 5.0.
$covarianceSampReturns the sample covariance of two numeric expressions.
New in version 5.0.
$denseRankReturns the document position (known as the rank) relative to other documents in the $setWindowFields stage partition. There are no gaps in the ranks. Ties receive the same rank.
New in version 5.0.
$derivativeReturns the average rate of change within the specified window.
New in version 5.0.
$documentNumberReturns the position of a document (known as the document number) in the $setWindowFields stage partition. Ties result in different adjacent document numbers.
New in version 5.0.
$expMovingAvgReturns the exponential moving average for the numeric expression.
New in version 5.0.
$firstReturns the result of an expression for the first document in a group or window.
Changed in version 5.0: Available in the $setWindowFields stage.
$integralReturns the approximation of the area under a curve.
New in version 5.0.
$lastReturns the result of an expression for the last document in a group or window.
Changed in version 5.0: Available in the $setWindowFields stage.
$linearFillFills null and missing fields in a window using linear interpolation based on surrounding field values.
Available in the $setWindowFields stage.
New in version 5.3.
$locfLast observation carried forward. Sets values for null and missing fields in a window to the last non-null value for the field.
Available in the $setWindowFields stage.
New in version 5.2.
$maxReturns the maximum value that results from applying an expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$minReturns the minimum value that results from applying an expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$minNReturns an aggregation of the n minimum valued elements in a group. Distinct from the $minN array operator.
New in version 5.2.
Available in $group, $setWindowFields and as an expression.
$pushReturns an array of values that result from applying an expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$rankReturns the document position (known as the rank) relative to other documents in the $setWindowFields stage partition.
New in version 5.0.
$shiftReturns the value from an expression applied to a document in a specified position relative to the current document in the $setWindowFields stage partition.
New in version 5.0.
$stdDevPopReturns the population standard deviation that results from applying a numeric expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$stdDevSampReturns the sample standard deviation that results from applying a numeric expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$sumReturns the sum that results from applying a numeric expression to each document.
Changed in version 5.0: Available in the $setWindowFields stage.
$topReturns the top element within a group according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.
$topNReturns an aggregation of the top n fields within a group, according to the specified sort order.
New in version 5.2.
Available in the $group and $setWindowFields stages.

Index of Expression Operators