MongoDB聚合运算符:$reduce

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 : 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值