On this page本页内容
$reduce¶New in version 3.4.版本3.4中的新功能。
Applies an expression to each element in an array and combines them into a single value.将表达式应用于数组中的每个元素,并将它们组合为单个值。
$reduce has the following syntax:语法如下所示:
input | 
array | 
 
 
  | 
initialValue | 
value set before in is applied to the first element of the input array.in之前设置的初始累积value应用于input数组的第一个元素。 | |
in | 
 
  | 
If 如果input resolves to an empty array, $reduce returns initialValue.input解析为空数组,$reduce返回initialValue。
"abc" | |
{ "sum" : 15, "product" : 48 } | |
[ 1, 2, 3, 4, 5, 6 ] | 
A collection named 名为events contains the events of a probability experiment. events的集合包含概率实验的事件。Each experiment can have multiple 每个实验可以有多个events, such as rolling a die several times or drawing several cards (without replacement) in succession to achieve a desired result. events,例如滚动模具几次或连续绘制几张卡片(无需更换),以达到预期的结果。In order to obtain the overall probability of the experiment, we will need to multiply the probability of each event in the experiment.为了得到实验的总体概率,我们需要乘以实验中每个事件的概率。
Steps:
$group to group by the experimentId and use $push to create an array with the probability of each event.$group 按experimentId分组,并使用$push创建一个包含每个事件概率的数组。$reduce with $multiply to multiply and combine the elements of probabilityArr into a single value and project it.$reduce和$multiply将probabilityArr的元素相乘并组合成一个值并进行投影。The operation returns the following:该操作返回以下内容:
A collection named 名为clothes contains the following documents:clothes的集合包含以下文档:
Each document contains a 每个文档都包含一个discounts array containing the currently available percent-off coupons for each item. discounts数组,其中包含每个项目当前可用的折扣券百分比。If each discount can be applied to the product once, we can calculate the lowest price by using 如果每个折扣可以应用于产品一次,我们可以使用$reduce to apply the following formula for each element in the discounts array: (1 - discount) * price.$reduce计算最低价格,对discounts 数组中的每个元素应用以下公式:(1 - discount) * price。
The operation returns the following:该操作返回以下内容:
A collection named 名为people contains the following documents:people的集合包含以下文档:
The following example reduces the 以下示例将字符串hobbies array of strings into a single string bio:hobbies数组简化为单个字符串bio:
The operation returns the following:该操作返回以下内容:
A collection named 名为matrices contains the following documents:matrices的集合包含以下文档:
The following example collapses the two dimensional arrays into a single array 以下示例将二维数组折叠为单个数组collapsed:collapsed:
The operation returns the following:该操作返回以下内容:
The following example performs the same two dimensional array collapse as the example above, but also creates a new array containing only the first element of each array.下面的示例执行与上述示例相同的二维数组折叠,但也创建了一个只包含每个数组的第一个元素的新数组。
The operation returns the following:该操作返回以下内容: