MongoDB聚合运算符:$exp

慈云数据 1年前 (2024-03-20) 技术支持 80 0

文章目录

    • 语法
    • 使用
    • 举例

      $exp聚合运算符返回自然常数或欧拉数e的幂值(次方)的结果

      语法

      { $exp:  }
      

      为指数,可以是任何数值表达式。

      MongoDB聚合运算符:$exp
      (图片来源网络,侵删)

      使用

      如果参数为null或引用的字段不存在,$exp返回null,如果参数解析为NaN则$exp也返回NaN,如下:

      参数结果
      {$exp: 0}1
      {$exp: 2}7.38905609893065
      { $exp: -2 }0.1353352832366127

      举例

      使用下面的脚本创建accounts集合

      MongoDB聚合运算符:$exp
      (图片来源网络,侵删)
      db.accounts.insertMany( [
         { _id: 1, interestRate: .08, presentValue: 10000 },
         { _id: 2, interestRate: .0825, presentValue: 250000 },
         { _id: 3, interestRate: .0425, presentValue: 1000 }
      ] )
      

      下面的例子计算连续复利的实际利率:

      db.accounts.aggregate( [ { $project: { effectiveRate: { $subtract: [ { $exp: "$interestRate"}, 1 ] } } } ] )
      

      返回结果如下:

      { "_id" : 1, "effectiveRate" : 0.08328706767495864 }
      { "_id" : 2, "effectiveRate" : 0.08599867343905654 }
      { "_id" : 3, "effectiveRate" : 0.04341605637367807 }
      

      使用下面的脚本创建``集合:

微信扫一扫加客服

微信扫一扫加客服