Search code examples
arraysmongodbmongodb-queryaggregation-frameworkmongodb-shell

$addFields and calculation not working - mongodb shell






db.Hours.aggregate(
  {$addFields: {TrueAmbientTemp: { {$add : [-8 , {$multiply : ["$AmbientTemp" , 47]}]}}}}
)

I am trying to add a new field TrueAmbientTemp which is a calculation field. The above give an error.


Solution

  • You miss some semicolons.

    db.collection.aggregate({
      $addFields: {
        TrueAmbientTemp: {
          $add: [
            -8,
            {
              $multiply: [
                "$AmbientTemp",
                47
              ]
            }
          ]
        }
      }
    })
    

    Example:mongoplayground

    update:you can change update to updateMany

    db.collection.update({},
    [
      {
        $addFields: {
          TrueAmbientTemp: {
            $add: [
              -8,
              {
                $multiply: [
                  "$AmbientTemp",
                  47
                ]
              }
            ]
          }
        }
      }
    ])
    

    Example:mongoplayground