Aggregation Pipeline Quick Reference聚合管道快速参考

On this page本页内容

Note

For details on specific operator, including syntax and examples, click on the specific operator to go to its 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描述
$addFields

Adds 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的别名。

$bucket Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.根据指定的表达式和存储桶边界,将传入文档分类到称为存储桶的组中。
$bucketAuto Categorizes 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.为了将文档平均分配到指定数量的存储桶中,将自动确定存储桶边界。
$collStats Returns statistics regarding a collection or view.返回有关集合或视图的统计信息。
$count Returns a count of the number of documents at this stage of the aggregation pipeline.返回聚合管道此阶段的文档数计数。
$facet Processes 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.支持创建多方面的聚合,能够在单个阶段中跨多个维度或方面表征数据。
$geoNear Returns 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.输出文档包括一个附加的距离字段,并且可以包括一个位置标识符字段。
$graphLookup Performs 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.向每个输出文档添加一个新的数组字段,该字段包含该文档递归搜索的遍历结果。
$group Groups 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.输出文档仅包含标识符字段和累计字段(如果指定)。
$indexStats Returns statistics regarding the use of each index for the collection.返回有关集合中每个索引使用情况的统计信息。
$limit Passes 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个文档之后)。
$listSessions Lists all sessions that have been active long enough to propagate to the system.sessions collection.列出所有活动时间足以传播到system.sessions集合的会话。
$lookup Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing.对同一数据库中的另一个集合执行左外部联接,以从“联接”集合中筛选文档进行处理。
$match Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. 过滤文档流,只允许匹配的文档未经修改地传递到下一个管道阶段。$match uses standard MongoDB queries. $match使用标准MongoDB查询。For each input document, outputs either one document (a match) or zero documents (no match).对于每个输入文档,输出一个文档(匹配)或零个文档(不匹配)。
$merge

Writes 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中的新功能。

$out Writes 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阶段,它必须是管道中的最后一个阶段。
$planCacheStats Returns plan cache information for a collection.返回集合的计划缓存信息。
$project

Reshapes 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

$redact Reshapes 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.对于每个输入文档,输出一个或零个文档。
$replaceRoot

Replaces 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.$replaceWith$replaceRoot阶段的别名。

$replaceWith

Replaces 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.$replaceWith$replaceRoot阶段的别名。

$sample Randomly selects the specified number of documents from its input.从输入中随机选择指定数量的文档。
$sampleRate Randomly 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.虽然每次运行时选择的文档的确切数量各不相同,但选择的数量近似于以文档总数百分比表示的采样率。
$set

Adds 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.$set$addFields阶段的别名。

$skip Skips 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个文档之后)。
$sort Reorders the document stream by a specified sort key. 按指定的排序键对文档流重新排序。Only the order changes; the documents remain unmodified. 只有顺序改变;这些文件没有修改。For each input document, outputs one document.对于每个输入文档,输出一个文档。
$sortByCount Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档数。
$unionWith

Performs a union of two collections; i.e. combines pipeline results from two collections into a single result set.执行两个集合的并集;i、 e.将来自两个集合的管道结果合并到单个结果集中。

New in version 4.4.版本4.4中的新功能。

$unset

Removes/excludes fields from documents.从文档中删除/排除字段。

$unset is an alias for $project stage that removes fields.$unset是删除字段的$project阶段的别名。

$unwind Deconstructs 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描述
$currentOp Returns information on active and/or dormant operations for the MongoDB deployment.返回有关MongoDB部署的活动和/或休眠操作的信息。
$listLocalSessions Lists 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集合。

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

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

Command命令mongo Shell Methods壳方法
findAndModify
update

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 via $$通过$$访问Brief Description简述
NOW $$NOW Returns 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_TIME Returns 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 $$ROOT References the root document, i.e. the top-level document.引用根文档,即顶级文档。
CURRENT $$CURRENT References the start of the field path, which by default is ROOT but can be changed.引用字段路径的开头,默认情况下,该路径为ROOT,但可以更改。
REMOVE $$REMOVE Allows for the conditional exclusion of fields. 允许有条件地排除字段。(Available in 3.6+)
DESCEND $$DESCEND One of the allowed results of a $redact expression.$redact表达式允许的结果之一。
PRUNE $$PRUNE One of the allowed results of a $redact expression.$redact表达式允许的结果之一。
KEEP $$KEEP One of the allowed results of a $redact expression.$redact表达式允许的结果之一。

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描述
$abs Returns the absolute value of a number.返回数字的绝对值。
$add Adds 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.接受任意数量的参数表达式,但最多一个表达式可以解析为一个日期。
$ceil Returns the smallest integer greater than or equal to the specified number.返回大于或等于指定数字的最小整数。
$divide Returns the result of dividing the first number by the second. Accepts two argument expressions.返回第一个数除以第二个数的结果。接受两个参数表达式。
$exp Raises e to the specified exponent.e幂乘到指定的指数。
$floor Returns the largest integer less than or equal to the specified number.返回小于或等于指定数字的最大整数。
$ln Calculates the natural log of a number.计算数字的自然对数。
$log Calculates the log of a number in the specified base.计算指定基数中某个数字的对数。
$log10 Calculates the log base 10 of a number.计算一个数字的对数基数10。
$mod Returns the remainder of the first number divided by the second. 返回第一个数除以第二个数的余数。Accepts two argument expressions.接受两个参数表达式。
$multiply Multiplies numbers to return the product. 将数字相乘以返回产品。Accepts any number of argument expressions.接受任意数量的参数表达式。
$pow Raises a number to the specified exponent.将数字提升到指定的指数。
$round Rounds a number to to a whole integer or to a specified decimal place.将数字舍入为整数或指定的小数位。
$sqrt Calculates the square root.计算平方根。
$subtract Returns 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.接受两个参数表达式。如果这两个值是日期和数字,请首先指定日期参数,因为从数字中减去日期没有意义。
$trunc Truncates a number to a whole integer or to a specified decimal place.将数字截断为整数或指定的小数位。

Array Expression Operators数组表达式运算符

$arrayElemAtReturns the element at the specified array index.返回指定数组索引处的元素。
$arrayToObject Converts an array of key value pairs to a document.将键值对数组转换为文档。
$concatArrays Concatenates arrays to return the concatenated array.连接数组以返回连接的数组。
$filter Selects a subset of the array to return an array with only the elements that match the filter condition.选择数组的子集以返回仅包含与筛选条件匹配的元素的数组。
$first Returns the first array element. 返回第一个数组元素。Distinct from $first accumulator.不同于$first累加器。
$in Returns a boolean indicating whether a specified value is in an array.返回一个布尔值,指示指定值是否在数组中。
$indexOfArray Searches 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.如果未找到子字符串,则返回-1
$isArray Determines if the operand is an array. 确定操作数是否为数组。Returns a boolean.返回一个布尔值。
$last Returns the last array element. 返回最后一个数组元素。Distinct from $last accumulator.有别于$last累加器。
$map Applies a subexpression to each element of an array and returns the array of resulting values in order. 将子表达式应用于数组的每个元素,并按顺序返回结果值数组。Accepts named parameters.接受命名参数。
$objectToArray Converts a document to an array of documents representing key-value pairs.将文档转换为表示键值对的文档数组。
$range Outputs an array containing a sequence of integers according to user-defined inputs.根据用户定义的输入输出包含整数序列的数组。
$reduce Applies an expression to each element in an array and combines them into a single value.将表达式应用于数组中的每个元素,并将它们组合为单个值。
$reverseArray Returns an array with the elements in reverse order.返回元素顺序相反的数组。
$size Returns the number of elements in the array. 返回数组中的元素数。Accepts a single expression as argument.接受单个表达式作为参数。
$slice Returns a subset of an array.返回数组的子集。
$zip Merge 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描述
$and Returns true only when all its expressions evaluate to true. 仅当其所有表达式的计算结果为true时,才返回trueAccepts any number of argument expressions.接受任意数量的参数表达式。
$not Returns the boolean value that is the opposite of its argument expression. 返回与其参数表达式相反的布尔值。Accepts a single argument expression.接受单个参数表达式。
$or Returns 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
$eq Returns true if the values are equivalent.如果值相等,则返回true
$gt Returns true if the first value is greater than the second.如果第一个值大于第二个值,则返回true
$gte Returns true if the first value is greater than or equal to the second.如果第一个值大于或等于第二个值,则返回true
$lt Returns true if the first value is less than the second.如果第一个值小于第二个值,则返回true
$lte Returns true if the first value is less than or equal to the second.如果第一个值小于或等于第二个值,则返回true
$ne Returns true if the values are not equivalent.如果值不相等,则返回true

Conditional Expression Operators条件表达式运算符

Name名称Description描述
$cond A 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.接受有序列表中的三个表达式或三个命名参数。
$ifNull Returns 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. Null结果包含未定义值或缺少字段的实例。Accepts two expressions as arguments. 接受两个表达式作为参数。The result of the second expression can be null.第二个表达式的结果可以为null
$switch Evaluates 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描述
$accumulator

Defines a custom accumulator function.定义自定义累加器函数。

New in version 4.4.版本4.4中的新功能。

$function

Defines 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描述
$binarySize Returns the size of a given string or binary data value’s content in bytes.返回给定字符串或二进制数据值内容的大小(字节)。
$bsonSize Returns the size in bytes of a given document (i.e. bsontype Object) when encoded as BSON.返回编码为BSON时给定文档(即bsontypeObject)的大小(以字节为单位)。

Date Expression Operators日期表达式运算符

The following operators returns date objects or components of a date object:以下运算符返回日期对象或日期对象的组件:

Name名称Description描述
$dateFromParts Constructs a BSON Date object given the date’s constituent parts.给定日期的组成部分,构造BSON Date对象。
$dateFromString Converts a date/time string to a date object.将日期/时间字符串转换为日期对象。
$dateToParts Returns a document containing the constituent parts of a date.返回包含日期组成部分的文档。
$dateToString Returns the date as a formatted string.以格式化字符串的形式返回日期。
$dayOfMonth Returns the day of the month for a date as a number between 1 and 31.以1到31之间的数字返回日期的月份日期。
$dayOfWeek Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday).以1(星期日)到7(星期六)之间的数字形式返回日期的星期几。
$dayOfYear Returns the day of the year for a date as a number between 1 and 366 (leap year).以介于1和366(闰年)之间的数字返回日期的日期。
$hour Returns the hour for a date as a number between 0 and 23.以0到23之间的数字返回日期的小时数。
$isoDayOfWeek Returns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday).返回ISO 8601格式的工作日编号,范围从1(星期一)到7(星期日)。
$isoWeek Returns 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开始,以包含一年中第一个星期四的周(周一到周日)为单位。
$isoWeekYear Returns 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 8601)。
$millisecond Returns the milliseconds of a date as a number between 0 and 999.以介于0和999之间的数字形式返回日期的毫秒数。
$minute Returns the minute for a date as a number between 0 and 59.以0到59之间的数字形式返回日期的分钟。
$month Returns the month for a date as a number between 1 (January) and 12 (December).将日期的月份返回为介于1(一月)和12(十二月)之间的数字。
$second Returns the seconds for a date as a number between 0 and 60 (leap seconds).以0到60之间的数字(闰秒)返回日期的秒数。
$toDate

Converts value to a Date.将值转换为日期。

New in version 4.0.版本4.0中的新功能。

$week Returns 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(闰年)之间的数字返回。
$year Returns the year for a date as a number (e.g. 2014).以数字形式返回日期的年份(例如2014年)。

The following arithmetic operators can take date operands:以下算术运算符可以采用日期操作数:

Name名称Description描述
$add 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.接受任意数量的参数表达式,但最多一个表达式可以解析为一个日期。
$subtract Returns 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描述
$literal Return 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 $ to avoid parsing as a field path.例如,对以$开头的字符串使用$literal达式以避免解析为字段路径。

Object Expression Operators对象表达式运算符

Name名称Description描述
$mergeObjects

Combines multiple documents into a single document.将多个文档合并为一个文档。

New in version 3.6.版本3.6中的新功能。

$objectToArray

Converts a document to an array of documents representing key-value pairs.将文档转换为表示键值对的文档数组。

New in version 3.6.版本3.6中的新功能。

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. 如果set操作返回一个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描述
$allElementsTrue Returns true if no element of a set evaluates to false, otherwise, returns false. 如果集合中没有元素的计算结果为false,则返回true,否则返回falseAccepts a single argument expression.接受单个参数表达式。
$anyElementTrue Returns true if any elements of a set evaluate to true; otherwise, returns false. 如果集合的任一元素的计算结果为true,则返回true;否则,返回falseAccepts a single argument expression.接受单个参数表达式。
$setDifference Returns 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.只接受两个参数表达式。
$setEquals Returns true if the input sets have the same distinct elements. 如果输入集具有相同的各不相同元素,则返回trueAccepts two or more argument expressions.接受两个或多个参数表达式。
$setIntersection Returns a set with elements that appear in all of the input sets. 返回包含所有输入集中出现的元素的集合。Accepts any number of argument expressions.接受任意数量的参数表达式。
$setIsSubset Returns 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. 如果第一个集合的所有元素都出现在第二个集合中,包括第一个集合等于第二个集合时,亦即,不是严格的子集,则返回trueAccepts exactly two argument expressions.只接受两个参数表达式。
$setUnion Returns 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.$concat行为定义良好,与使用的字符无关。

Name名称Description描述
$concat Concatenates any number of strings.连接任意数量的字符串。
$dateFromString Converts a date/time string to a date object.将日期/时间字符串转换为日期对象。
$dateToString Returns the date as a formatted string.以格式化字符串的形式返回日期。
$indexOfBytes Searches 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
$indexOfCP Searches 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
$ltrim

Removes whitespace or the specified characters from the beginning of a string.删除字符串开头的空白或指定字符。

New in version 4.0.版本4.0中的新功能。

$regexFind

Applies a regular expression (regex) to a string and returns information on the first matched substring.将正则表达式(regex)应用于字符串并返回有关第一个匹配子字符串的信息。

New in version 4.2.版本4.2中的新功能。

$regexFindAll

Applies a regular expression (regex) to a string and returns information on the all matched substrings.将正则表达式(regex)应用于字符串并返回有关所有匹配子字符串的信息。

New in version 4.2.版本4.2中的新功能。

$regexMatch

Applies 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中的新功能。

$replaceOne

Replaces the first instance of a matched string in a given input.替换给定输入中匹配字符串的第一个实例。

New in version 4.4.版本4.4中的新功能。

$replaceAll

Replaces all instances of a matched string in a given input.替换给定输入中匹配字符串的所有实例。

New in version 4.4.版本4.4中的新功能。

$rtrim

Removes whitespace or the specified characters from the end of a string.从字符串末尾删除空格或指定字符。

New in version 4.0.版本4.0中的新功能。

$split Splits 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.返回子字符串数组。如果在字符串中找不到分隔符,则返回包含原始字符串的数组。
$strLenBytes Returns the number of UTF-8 encoded bytes in a string.返回字符串中UTF-8编码的字节数。
$strLenCP Returns the number of UTF-8 code points in a string.返回字符串中UTF-8 代码点的数目。
$strcasecmp Performs 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
$substr Deprecated. 不赞成。Use $substrBytes or $substrCP.使用$substrBytes$substrCP
$substrBytes Returns 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字节索引(从零开始)处的字符开始,并持续指定的字节数。
$substrCP Returns 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)索引(从零开始)处的字符开始,并按指定的代码点数继续。
$toLower Converts a string to lowercase. 将字符串转换为小写。Accepts a single argument expression.接受单个参数表达式。
$toString

Converts value to a string.将值转换为字符串。

New in version 4.0.版本4.0中的新功能。

$trim

Removes whitespace or the specified characters from the beginning and end of a string.从字符串的开头和结尾删除空格或指定字符。

New in version 4.0.版本4.0中的新功能。

$toUpper Converts a string to uppercase. 将字符串转换为大写。Accepts a single argument expression.接受单个参数表达式。

Text Expression Operator文本表达式运算符

Name名称Description描述
$meta Access 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描述
$sin Returns the sine of a value that is measured in radians.返回以弧度为单位测量的值的正弦值。
$cos Returns the cosine of a value that is measured in radians.返回以弧度度量的值的余弦。
$tan Returns the tangent of a value that is measured in radians.返回以弧度为单位测量的值的切线。
$asin Returns the inverse sin (arc sine) of a value in radians.返回以弧度为单位的值的反正弦(弧正弦)。
$acos Returns the inverse cosine (arc cosine) of a value in radians.返回以弧度为单位的值的反余弦(弧余弦)。
$atan Returns the inverse tangent (arc tangent) of a value in radians.返回以弧度为单位的值的反切线(反正切)。
$atan2 Returns 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分别是传递给表达式的第一个值和第二个值。
$asinh Returns the inverse hyperbolic sine (hyperbolic arc sine) of a value in radians.返回以弧度为单位的值的反双曲正弦(双曲弧正弦)。
$acosh Returns the inverse hyperbolic cosine (hyperbolic arc cosine) of a value in radians.返回以弧度为单位的值的反双曲余弦(双曲弧余弦)。
$atanh Returns the inverse hyperbolic tangent (hyperbolic arc tangent) of a value in radians.返回以弧度为单位的值的反双曲正切(双曲反正切)。
$degreesToRadians Converts a value from degrees to radians.将值从度转换为弧度。
$radiansToDegrees Converts a value from radians to degrees.将值从弧度转换为度。

Type Expression Operators类型表达式运算符

Name名称Description描述
$convert

Converts a value to a specified type.将值转换为指定的类型。

New in version 4.0.版本4.0中的新功能。

$isNumber

Returns 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中的新功能。

$toBool

Converts value to a boolean.将值转换为boolean

New in version 4.0.版本4.0中的新功能。

$toDate

Converts value to a Date.将值转换为Date

New in version 4.0.版本4.0中的新功能。

$toDecimal

Converts value to a Decimal128.将值转换为Decimal128

New in version 4.0.版本4.0中的新功能。

$toDouble

Converts value to a double.将值转换为double

New in version 4.0.版本4.0中的新功能。

$toInt

Converts value to an integer.将值转换为integer

New in version 4.0.版本4.0中的新功能。

$toLong

Converts value to a long.将值转换为long

New in version 4.0.版本4.0中的新功能。

$toObjectId

Converts value to an ObjectId.将值转换为ObjectId

New in version 4.0.版本4.0中的新功能。

$toString

Converts value to a string.将值转换为string

New in version 4.0.版本4.0中的新功能。

$type Return the BSON data type of the field.返回字段的BSON数据类型。

Accumulators累加器 ($group)

Available for use in the $group stage, accumulators are operators that maintain their state (e.g. totals, maximums, minimums, and related data) as documents progress through the pipeline.可在$group阶段使用,累加器是在文档通过管道时保持其状态(例如总计、最大值、最小值和相关数据)的运算符。

When used as accumulators in the $group stage, these operators take as input a single expression, evaluating the expression once for each input document, and maintain their stage for the group of documents that share the same group key.$group阶段中用作累加器时,这些运算符将单个表达式作为输入,对每个输入文档计算一次表达式,并为共享同一组密钥的文档组维护其阶段。

Name名称Description描述
$accumulator Returns the result of a user-defined accumulator function.返回用户定义的累加器函数的结果。
$addToSet Returns an array of unique expression values for each group. Order of the array elements is undefined.返回每个组的唯一表达式值数组。数组元素的顺序未定义。
$avg Returns an average of numerical values. Ignores non-numeric values.返回数值的平均值。忽略非数值。
$first

Returns a value from the first document for each group. 从每个组的第一个文档返回一个值。Order is only defined if the documents are in a defined order.仅当文档的顺序已定义时,才定义顺序。

Distinct from the $first array operator.$first数组运算符不同。

$last

Returns a value from the last document for each group. 从每个组的最后一个文档返回一个值。Order is only defined if the documents are in a defined order.仅当文档的顺序已定义时,才定义顺序。

Distinct from the $last array operator.$last数组运算符不同。

$max Returns the highest expression value for each group.返回每个组的最高表达式值。
$mergeObjects Returns a document created by combining the input documents for each group.返回通过组合每个组的输入文档创建的文档。
$min Returns the lowest expression value for each group.返回每个组的最低表达式值。
$push Returns an array of expression values for each group.返回每个组的表达式值数组。
$stdDevPop Returns the population standard deviation of the input values.返回输入值的总体标准偏差。
$stdDevSamp Returns the sample standard deviation of the input values.返回输入值的样本标准偏差。
$sum Returns a sum of numerical values. Ignores non-numeric values.返回数值的总和。忽略非数值。

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 3.2.在版本3.2中更改。

The following accumulator operators are also available in the $project, $addFields, and $set stages.以下累加器运算符也可在$project$addFields$set阶段中使用。

Name名称Description描述
$avg Returns an average of the specified expression or list of expressions for each document. 返回每个文档的指定表达式或表达式列表的平均值。Ignores non-numeric values.忽略非数值。
$max Returns the maximum of the specified expression or list of expressions for each document返回每个文档的指定表达式或表达式列表的最大值
$min Returns the minimum of the specified expression or list of expressions for each document返回每个文档的指定表达式或表达式列表的最小值
$stdDevPop Returns the population standard deviation of the input values.返回输入值的总体标准偏差。
$stdDevSamp Returns the sample standard deviation of the input values.返回输入值的样本标准偏差。
$sum Returns a sum of numerical values. 返回数值的总和。Ignores non-numeric values.忽略非数值。

Variable Expression Operators变量表达式运算符

Name名称Description描述
$let

Defines 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.接受任意数量的参数表达式。

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