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. db.collection.aggregate()方法中,管道阶段显示在一个数组中。Documents pass through the stages in sequence. 文件按顺序通过各个阶段。All except the $out, $merge, and $geoNear stages can appear multiple times in a pipeline.$out$merge$geoNear阶段外,所有阶段都可以在管道中多次出现。

db.collection.aggregate( [ { <stage> }, ... ] )
Stage阶段Description描述
$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.类似于$project$addFields对流中的每个文档进行重新整形;具体地说,通过将新字段添加到既包含输入文档中的现有字段又包含新添加字段的输出文档中。
$set is an alias for $addFields. $addFields的别名。
$bucketCategorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.根据指定的表达式和bucket边界,将传入的文档分类到称为bucket的组中。
$bucketAutoCategorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. 根据指定的表达式,将传入文档分类为特定数量的组,称为bucket。Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets.Bucket边界是自动确定的,目的是将文档平均分配到指定数量的Bucket中。
$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.此阶段在聚合管道中只能出现一次,并且必须作为第一个阶段出现。
$changeStreamSplitLargeEventSplits large change stream events that exceed 16 MB into smaller fragments returned in a change stream cursor.将超过16MB的大型变更流事件拆分为变更流游标中返回的较小片段。
You can only use $changeStreamSplitLargeEvent in a $changeStream pipeline and it must be the final stage in the pipeline. 只能在$changeStream管道中使用$changeStreamSplitTargetEvent,并且它必须是管道中的最后阶段。
$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. $count聚合累加器不同。
$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. 填充文档中的null字段值和缺少的字段值。
$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. 结合了地理空间数据的$match$sort$limit功能。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. 将未修改的前n个文档传递到管道,其中n是指定的限制。For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents).对于每个输入文档,输出一个文档(针对前n个文档)或零个文档(在前n个文件之后)。
$listSampledQueriesLists sampled queries for all collections or a specific collection.列出所有集合或特定集合的采样查询。
$listSearchIndexesReturns information about existing Atlas Search indexes on a specified collection. 返回有关指定集合上现有Atlas Search索引的信息。
$listSessionsLists all sessions that have been active long enough to propagate to the system.sessions collection.列出活动时间足以传播到system.sessions集合的所有会话。
$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. 使用标准的MongoDB查询。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. 若要使用$merge阶段,它必须是管道中的最后一个阶段。
New in version 4.2. 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.要使用$out阶段,它必须是管道中的最后一个阶段。
$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. 另请参阅$unset以删除现有字段。
$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. 包含$project$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. 该操作将替换输入文档中的所有现有字段,包括_id字段。Specify a document embedded in the input document to promote the embedded document to the top level.指定嵌入在输入文档中的文档,以将嵌入的文档提升到顶级。
$replaceWith is an alias for $replaceRoot stage. $replaceRoot阶段的别名。
$replaceWithReplaces a document with the specified embedded document. 用指定的嵌入文档替换文档。The operation replaces all existing fields in the input document, including the _id field. 该操作将替换输入文档中的所有现有字段,包括_id字段。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. Atlas集合中的一个或多个字段执行全文搜索。
Note
$search is only available for MongoDB Atlas clusters, and is not available for self-managed deployments. 仅适用于MongoDB Atlas集群,不适用于自管理部署。To learn more, see Atlas Search Aggregation Pipeline Stages. 要了解更多信息,请参阅Atlas搜索聚合管道阶段
$searchMetaReturns different types of metadata result documents for the Atlas Search query against an Atlas collection. 针对Atlas集合为Atlas Search查询返回不同类型的元数据结果文档。
Note
$searchMeta is only available for MongoDB Atlas clusters running MongoDB v4.4.9 or higher, and is not available for self-managed deployments. 仅适用于运行MongoDB v4.4.9或更高版本的MongoDB Atlas集群,不适用于自管理部署。To learn more, see Atlas Search Aggregation Pipeline Stages. 要了解更多信息,请参阅Atlas搜索聚合管道阶段
$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.$project类似,$set对流中的每个文档进行重新整形;具体地说,通过将新字段添加到既包含输入文档中的现有字段又包含新添加字段的输出文档中。
$set is an alias for $addFields stage. $addFields阶段的别名。
$setWindowFieldsGroups documents into windows and applies one or more operators to the documents in each window. 将文档分组到窗口中,并将一个或多个运算符应用于每个窗口中的文档。
New in version 5.0. 5.0版新增。
$skipSkips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. 跳过前n个文档,其中n是指定的跳过编号,并将未修改的其余文档传递到管道。For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents).对于每个输入文档,输出零个文档(对于前n个文档)或一个文档(如果在前n个文件之后)。
$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. 4.4版新增。
$unsetRemoves/excludes fields from documents.从文档中删除/排除字段。
$unset is an alias for $project stage that removes fields. 是删除字段的$project阶段的别名。
$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.对于每个输入文档,输出n个文档,其中n是数组元素的数量,对于空数组可以为零。

Stages阶段 (db.aggregate)

Starting in version 3.6, MongoDB also provides the db.aggregate() method:从3.6版本开始,MongoDB还提供了db.aggregate()方法:

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

The following stages use the db.aggregate() method and not the db.collection.aggregate() method.以下阶段使用db.aggregate()方法,而不是db.collection.aggregate()方法。

Stage阶段Description描述
$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.返回有关MongoDB部署的活动和/或休眠操作的信息。
$listLocalSessionsLists all active sessions recently in use on the currently connected mongos or mongod instance. 列出最近在当前连接的mongosmongod实例上使用的所有活动会话。These sessions may have not yet propagated to the system.sessions collection.这些会话可能尚未传播到system.sessions集合。
$documentsReturns literal documents from input values.从输入值返回字面量文档。

Stages Available for Updates可用于更新的阶段

Starting in MongoDB 4.2, you can use the aggregation pipeline for updates in:从MongoDB 4.2开始,您可以在以下位置使用聚合管道进行更新:

Command命令mongosh 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:对于更新,管道可以由以下阶段组成:

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.例如,"$user"指定user字段的字段路径,或"$user.name"指定"user.name"字段的字段通路。

"$<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."$<field>"相当于"$$CURRENT.<field>",其中CURRENT是一个系统变量,默认为当前对象的根,除非在特定阶段另有说明。

Aggregation Variables聚合变量

MongoDB provides various aggregation system variables for use in expressions. MongoDB提供了用于表达式的各种聚合系统变量To access variables, prefix the variable name with $$. 要访问变量,请在变量名前面加上$$For example:例如:

Variable变量Access using $$使用$$访问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+)(有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+)仅适用于复制集和分片集群。(有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.引用字段路径的开头,默认情况下为ROOT,但可以更改。
REMOVE$$REMOVEAllows for the conditional exclusion of fields. (Available in 3.6+)允许有条件地排除字段。(有3.6+版本可供选择)
DESCEND$$DESCENDOne of the allowed results of a $redact expression.$redact表达式允许的结果之一。
PRUNE$$PRUNEOne of the allowed results of a $redact expression.$redact表达式允许的结果之一。
KEEP$$KEEPOne of the allowed results of a $redact expression.$redact表达式允许的结果之一。
USER_ROLES$$USER_ROLESReturns the roles assigned to the current user.返回分配给当前用户的角色
For use cases that include USER_ROLES, see the find, aggregation, view, updateOne, updateMany, and findAndModify examples. 有关包括USER_ROLES的用例,请参阅findaggregation视图updateOneupdateManyfindAndModify示例。
New in version 7.0. 7.0版新增。

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. 然而,MongoDB解析以美元符号$开头的字符串字面量作为字段的路径,解析表达式对象中的数字/布尔字面量作为投影标志。To avoid parsing literals, use the $literal expression.为了避免解析字面量,请使用$literal表达式。

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. 如果表达式是数字或布尔文本,MongoDB将文本视为投影标志(例如,1true以包含字段),仅在$project阶段有效。To avoid treating numeric or boolean literals as projection flags, use the $literal expression to wrap the numeric or boolean literals.若要避免将数字或布尔字面量视为投影标志,请使用$literal表达式包装数字或布尔文本。

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.如果参数是字面量数组,为了避免解析歧义,必须将字面量数组包装在$literal表达式中,或者保留指定参数列表的外部数组。

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.e幂乘到指定的指数。
$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.计算一个数字的对数基数10。
$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.$firstN累加器不同。
$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. 在数组中搜索指定值的引用,并返回第一个引用的数组索引。Array indexes start at zero.数组索引从零开始。
$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.$lastN累加器不同。
$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. 返回数组中最大的n个值。Distinct from the $maxN accumulator.$maxN累加器不同。
$minNReturns the n smallest values in an array. 返回数组中的n个最小值。Distinct from the $minN accumulator.$minN累加器不同。
$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. 除了false布尔值之外,布尔表达式还将以下值计算为falsenull0undefined值。The Boolean expression evaluates all other values as true, including non-zero numeric values and arrays.布尔表达式将所有其他值计算为true,包括非零数值和数组。

Name名称Description描述
$andReturns true only when all its expressions evaluate to true. 仅当其所有表达式的计算结果均为true时才返回trueAccepts 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. 当其任何表达式的计算结果为true时,返回trueAccepts any number of argument expressions.接受任意数量的参数表达式。

Comparison Expression Operators比较表达式运算符

Comparison expressions return a boolean except for $cmp which returns a number.比较表达式返回一个布尔值,但$cmp返回一个数字。

The comparison expressions take two argument expressions and compare both value and type, using the specified BSON comparison order for values of different types.比较表达式采用两个参数表达式,并对不同类型的值使用指定的BSON比较顺序来比较值和类型。

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.如果两个值相等,则返回0;如果第一个值大于第二个值,则返回1;如果第一值小于第二个,则返回-1
$eqReturns true if the values are equivalent.如果值相等,则返回true
$gtReturns true if the first value is greater than the second.如果第一个值大于第二个值,则返回true
$gteReturns true if the first value is greater than or equal to the second.如果第一个值大于或等于第二个值,则返回true
$ltReturns true if the first value is less than the second.如果第一个值小于第二个值,则返回true
$lteReturns true if the first value is less than or equal to the second.如果第一个值小于或等于第二个值,则返回true
$neReturns true if the values are not equivalent.如果值相等,则返回true

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结果,如果第一个表达式导致null结果,则返回第二个表达式的结果。Null result encompasses instances of undefined values or missing fields. Null结果包含未定义值或缺少字段的实例。Accepts two expressions as arguments. 接受两个表达式作为参数。The result of the second expression can be null.第二个表达式的结果可以为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.当它找到一个计算结果为true的表达式时,$switch执行指定的表达式并脱离控制流。

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

Name名称Description描述
$accumulatorDefines a custom accumulator function. 定义自定义累加器函数。
New in version 4.4. 4.4版新增。
$functionDefines a custom function. 定义自定义函数。
New in version 4.4. 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.当编码为BSON时,返回给定文档(即bsontype对象)的大小(以字节为单位)。

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.构造给定日期组成部分的BSON Date对象。
$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.以介于1和31之间的数字形式返回日期的月份日期。
$dayOfWeekReturns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday).以介于1(星期日)和7(星期六)之间的数字形式返回日期的星期几。
$dayOfYearReturns the day of the year for a date as a number between 1 and 366 (leap year).以介于1和366(闰年)之间的数字形式返回日期的日期。
$hourReturns the hour for a date as a number between 0 and 23.以0到23之间的数字形式返回日期的小时数。
$isoDayOfWeekReturns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday).返回ISO 8601格式的工作日编号,范围从1(周一)到7(周日)。
$isoWeekReturns the week number in ISO 8601 format, ranging from 1 to 53. 返回ISO 8601格式的周数,范围从153Week numbers start at 1 with the week (Monday through Sunday) that contains the year's first Thursday.周数从1开始,包含一年中第一个星期四的一周(星期一到星期日)。
$isoWeekYearReturns the year number in ISO 8601 format. 返回ISO 8601格式的年份号。The year starts with the Monday of week 1 (ISO 8601) and ends with the Sunday of the last week (ISO 8601).一年从第一周的星期一开始(ISO 8601),到最后一周的星期日结束(ISO 860 1)。
$millisecondReturns the milliseconds of a date as a number between 0 and 999.以0到999之间的数字形式返回日期的毫秒数。
$minuteReturns the minute for a date as a number between 0 and 59.以0到59之间的数字形式返回日期的分钟数。
$monthReturns the month for a date as a number between 1 (January) and 12 (December).以介于1(一月)和12(十二月)之间的数字形式返回日期的月份。
$secondReturns the seconds for a date as a number between 0 and 60 (leap seconds).以介于0和60(闰秒)之间的数字形式返回日期的秒数。
$toDateConverts value to a Date.
New in version 4.0. 将值转换为Date。4.0版新增。
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).返回日期的周数,该数字介于0(一年中第一个星期日之前的部分周)和53(闰年)之间。
$yearReturns the year for a date as a number (e.g. 2014).以数字形式返回日期的年份(例如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.例如,对以美元符号($)开头的字符串使用$literal表达式,以避免将其解析为字段路径。

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 ($). 您可以使用$getField来检索名称包含句点(.)或以美元符号($)开头的字段的值。
New in version 5.0. 5.0版新增。
$randReturns a random float between 0 and 1返回0和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 ($). 您可以使用$setField添加、更新或删除名称包含句点(.)或以美元符号($)开头的字段。
New in version 5.0. 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.Set表达式会忽略每个输入数组中的重复项和元素的顺序。

If the set operation returns a set, the operation filters out duplicates in the result to output an array that contains only unique entries. 如果set操作返回一个集合,则该操作会筛选出结果中的重复项,以输出仅包含唯一项的数组。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. 如果集合中没有任何元素的计算结果为false,则返回true,否则返回falseAccepts a single argument expression.接受单个参数表达式。
$anyElementTrueReturns true if any elements of a set evaluate to true; otherwise, returns false. 如果集合的任何元素的求值结果为true,则返回true;否则,返回falseAccepts 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. 如果输入集具有相同的不同元素,则返回trueAccepts 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. 如果第一个集合的所有元素都出现在第二个集合中,包括当第一个集合等于第二个集时,返回true;即不是严格的子集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除外)只对ASCII字符字符串具有定义良好的行为。

$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. 在字符串中搜索子字符串的出现,并返回第一个出现的UTF-8字节索引。If the substring is not found, returns -1.如果未找到子字符串,则返回-1
$indexOfCPSearches a string for an occurrence of a substring and returns the UTF-8 code point index of the first occurrence. 在字符串中搜索子字符串的出现,并返回第一个出现的UTF-8代码点索引。If the substring is not found, returns -1如果未找到子字符串,则返回-1
$ltrimRemoves whitespace or the specified characters from the beginning of a string. 删除字符串开头的空白或指定字符。
New in version 4.0. 4.0版新增。
$regexFindApplies a regular expression (regex) to a string and returns information on the first matched substring. 将正则表达式(regex)应用于字符串,并返回第一个匹配子字符串的信息。
New in version 4.2. 4.2版新增。
$regexFindAllApplies a regular expression (regex) to a string and returns information on the all matched substrings. 将正则表达式(regex)应用于字符串,并返回所有匹配子字符串的信息。
New in version 4.2. 4.2版新增。
$regexMatchApplies a regular expression (regex) to a string and returns a boolean that indicates if a match is found or not. 将正则表达式(regex)应用于字符串,并返回一个布尔值,指示是否找到匹配项。
New in version 4.2. 4.2版新增。
$replaceOneReplaces the first instance of a matched string in a given input. 替换给定输入中匹配字符串的第一个实例。
New in version 4.4. 4.4版新增。
$replaceAllReplaces all instances of a matched string in a given input. 替换给定输入中匹配字符串的所有实例。
New in version 4.4. 4.4版新增。
$rtrimRemoves whitespace or the specified characters from the end of a string. 删除字符串末尾的空白或指定字符。
New in version 4.0. 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.返回字符串中UTF-8编码的字节数。
$strLenCPReturns the number of UTF-8 code points in a string.返回字符串中UTF-8代码点的数目。
$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.执行不区分大小写的字符串比较并返回:如果两个字符串相等,则返回0;如果第一个字符串大于第二个字符串,则返回1;如果第一条字符串小于第二个,则返回-1
$substrDeprecated. 已弃用。Use $substrBytes or $substrCP.请改用$substrBytes$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.从字符串中指定的UTF-8字节索引(从零开始)处的字符开始,并持续指定的字节数。
$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.以字符串中指定的UTF-8代码点(CP)索引(从零开始)处的字符开头,并按指定的代码点数量继续。
$toLowerConverts a string to lowercase. Accepts a single argument expression.将字符串转换为小写。接受单个参数表达式。
$toStringConverts value to a string. 将值转换为字符串。
New in version 4.0. 4.0版新增。
$trimRemoves whitespace or the specified characters from the beginning and end of a string. 删除字符串开头和结尾的空白或指定字符。
New in version 4.0. 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.使用$degreesToRadians$radiansToDegrees在度数和弧度测量之间转换。

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.返回以弧度为单位的值的反正弦(arc-sine)。
$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.以弧度为单位返回y/x的反正切(反正切),其中yx分别是传递给表达式的第一个值和第二个值。
$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. 4.0版新增。
$isNumberReturns boolean true if the specified expression resolves to an integer, decimal, double, or long.如果指定的表达式解析为integerdecimaldoublelong,则返回布尔值true
Returns boolean false if the expression resolves to any other BSON type, null, or a missing field. 如果表达式解析为任何其他BSON类型、null或缺少字段,则返回布尔值false
New in version 4.4. 4.4版新增。
$toBoolConverts value to a boolean. 将值转换为boolean
New in version 4.0. 4.0版新增。
$toDateConverts value to a Date. 将值转换为Date
New in version 4.0. 4.0版新增。
$toDecimalConverts value to a Decimal128. 将值转换为Decimal128
New in version 4.0. 4.0版新增。
$toDoubleConverts value to a double. 将值转换为double
New in version 4.0. 4.0版新增。
$toIntConverts value to an integer. 将值转换为integer
New in version 4.0. 4.0版新增。
$toLongConverts value to a long. 将值转换为long
New in version 4.0. 4.0版新增。
$toObjectIdConverts value to an ObjectId. 将值转换为ObjectId
New in version 4.0. 4.0版新增。
$toStringConverts value to a string. 将值转换为string
New in version 4.0. 4.0版新增。
$typeReturn the BSON data type of the field.返回字段的BSON数据类型。

Accumulators 累加器($group, $bucket, $bucketAuto, $setWindowFields)

Aggregation accumulator operators:聚合累加器运算符:

  • Maintain their state as documents progress through the aggregation pipeline.在文档通过聚合管道时维护它们的状态。
  • Return totals, maxima, minima, and other values.返回总计、最大值、最小值和其他值。
  • Can be used in these aggregation pipeline stages:可用于以下聚合管道阶段:

Changed in version 5.05.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.05.0版更改: Available in the $setWindowFields stage. :在$setWindowFields阶段中可用。
$avgReturns an average of numerical values. Ignores non-numeric values. 返回数值的平均值。忽略非数值。
Changed in version 5.05.0版更改: Available in the $setWindowFields stage. :在$setWindowFields阶段中可用。
$bottomReturns the bottom element within a group according to the specified sort order. 根据指定的排序顺序返回组中的底部元素。
New in version 5.2. 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. 根据指定的排序顺序,返回组中最后n个字段的聚合。
New in version 5.2. 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.05.0版更改: Available in the $setWindowFields stage.
$firstNReturns an aggregation of the first n elements within a group. 返回一个组中前n个元素的聚合。Only meaningful when documents are in a defined order. 只有当文档按定义的顺序排列时才有意义。Distinct from the $firstN array operator. $firstN数组运算符不同。
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.05.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.05.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. 5.2版新增。
Available in $group, $setWindowFields and as an expression.
$medianReturns an approximation of the median, the 50th percentile, as a scalar value.
New in version 7.0. 7.0版新增。
This operator is available as an accumulator in these stages:此操作器在以下阶段可用作累加器: It is also available as an aggregation 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.05.0版更改: Available in the $setWindowFields stage.
$percentileReturns an array of scalar values that correspond to specified percentile values. 返回与指定百分位数相对应的标量值数组。
New in version 7.0. 7.0版新增。
This operator is available as an accumulator in these stages:此操作器在以下阶段可用作累加器: It is also available as an aggregation expression.
$pushReturns an array of expression values for documents in each group.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$stdDevPopReturns the population standard deviation of the input values.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$stdDevSampReturns the sample standard deviation of the input values.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$sumReturns a sum of numerical values. Ignores non-numeric values.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$topReturns the top element within a group according to the specified sort order.
New in version 5.2. 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. 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. 一些可作为$group阶段的累加器的运算符也可用于其他阶段,但不能用作累加器。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.05.0版更改.

The following accumulator operators are also available in the $project, $addFields, $set, and, starting in MongoDB 5.0, the $setWindowFields stages.以下累加器运算符也可用于$project$addFields$set,以及从MongoDB 5.0开始的$setWindowFields阶段。

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
$medianReturns an approximation of the median, the 50th percentile, as a scalar value.
New in version 7.0. 7.0版新增。
This operator is available as an accumulator in these stages:此操作器在以下阶段可用作累加器: It is also available as an aggregation expression.
$minReturns the minimum of the specified expression or list of expressions for each document返回每个文档的指定表达式或表达式列表的最小值
$percentileReturns an array of scalar values that correspond to specified percentile values. 返回与指定百分位数相对应的标量值数组。
New in version 7.0. 7.0版新增。
This operator is available as an accumulator in these stages:此操作器在以下阶段可用作累加器: It is also available as an aggregation expression. 它也可用作聚合表达式
$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.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.窗口是在$setWindowFields 阶段定义的,从MongoDB 5.0开始就可以使用。

The following window operators are available in the $setWindowFields stage.以下窗口运算符在$setWindowFields阶段中可用。

Name名称Description描述
$addToSetReturns an array of all unique values that results from applying an expression to each document.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$avgReturns the average for the specified expression. Ignores non-numeric values.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$bottomReturns the bottom element within a group according to the specified sort order.
New in version 5.2. 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. 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. 5.0版新增。
$covariancePopReturns the population covariance of two numeric expressions.
New in version 5.0. 5.0版新增。
$covarianceSampReturns the sample covariance of two numeric expressions.
New in version 5.0. 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. 5.0版新增。
$derivativeReturns the average rate of change within the specified window.
New in version 5.0. 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. 5.0版新增。
$expMovingAvgReturns the exponential moving average for the numeric expression.
New in version 5.0. 5.0版新增。
$firstReturns the result of an expression for the first document in a group or window.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$integralReturns the approximation of the area under a curve.
New in version 5.0. 5.0版新增。
$lastReturns the result of an expression for the last document in a group or window.
Changed in version 5.05.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. 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. 5.2版新增。
$maxReturns the maximum value that results from applying an expression to each document.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$minReturns the minimum value that results from applying an expression to each document.
Changed in version 5.05.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. 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.05.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. 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. 5.0版新增。
$stdDevPopReturns the population standard deviation that results from applying a numeric expression to each document.
Changed in version 5.05.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.05.0版更改: Available in the $setWindowFields stage.
$sumReturns the sum that results from applying a numeric expression to each document.
Changed in version 5.05.0版更改: Available in the $setWindowFields stage.
$topReturns the top element within a group according to the specified sort order.
New in version 5.2. 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. 5.2版新增。
Available in the $group and $setWindowFields stages.

Index of Expression Operators表达式运算符索引