MongoDB聚合运算符:$reduce
$reduce
聚合运算符将一个表达式应用于数组的每个元素并将它们合并为一个值。
语法
{
$reduce: {
input: <array>,
initialValue: <expression>,
in: <expression>
}
}
字段说明
input
:可解析为数组的表达式,作为$reduce
的输入,如果表达式为解析为null
或字段缺失,$reduce
返回null
。如果表达式无法解析为数组或null
或字段没有缺失,$reduce
返回错误。initialValue
:表达式,在对input
指定的数组进行计算累加前的初始值。in
:表达式,$reduce
按照从左到右的顺序对数组元素进行计算,如果用$reverseArray
包住输入值,相当于从右到左应用组合表达式。在计算 in 表达式期间,有两个变量可用:value
表示表达式累积值的变量。this
表示正在处理的元素的变量。
如果input
解析为空数组,$reduce
返回initialValue
举例说明:
例1
{
$reduce: {
input: ["a", "b", "c"],
initialValue: "",
in: {
$concat : ["$$value", "$$this"] }
}
}
结果:
"abc"
例2
{
$reduce: {
input: [ 1, 2, 3, 4 ],
initialValue: {
sum: 5, product: 2 },
in: {
sum: {
$add : ["$$value.sum", "$$this"] },
product: {
$multiply: [ "$$value.product", "$$this" ] }
}
}
}
结果:
{
"sum" : 15, "product" : 48 }
例3
{
$reduce: {
input: [ [ 3, 4 ], [ 5, 6 ] ],
initialValue: [ 1, 2 ],
in: {
$concatArrays : ["$$value", "$$this"] }
}
}
结果:
[ 1, 2, 3, 4, 5, 6 ]
举例
乘法
概率
名为events
的集合中包含了一些概率实验的事件,每个实验可以有多个事件events
,例如连续掷几次骰子或连续抽几张牌(不替换)以达到预期结果。为了得到实验的总概率,需要将实验中每个事件的概率相乘。
db.events.insertMany( [
{
_id : 1, type : "die", experimentId :"r5", description : "Roll a 5", eventNum : 1, probability : 0.16666666666667 },
{
_id : 2, type : "card", experimentId :"d3rc", description : "Draw 3 red cards", eventNum : 1, probability : 0.5 },
{
_id : 3, type : "card", experimentId :"d3rc", description : "Draw 3 red cards", eventNum : 2, probability : 0.49019607843137 },
{
_id : 4, type : "card", experimentId :"d3rc", description : "Draw 3 red cards", eventNum : 3, probability : 0.48 },
{
_id :