skip to Main Content

I would like to know how to subtract the nested array object field values in mongodb.

{
  Active: [
    {min: 1, energy: 24},
    {min: 2, energy: 34},
    {min: 3, energy: 65}
  ]
}

Expected output:
Difference: 65-24 = 41

I have tried this:

{
  $project: {
    Difference: {
      $subtract: ["$active.3.energy","$active.0.energy"]
    }
  }
}

query2:

{
  $project: {
    Difference: {
      $subtract: ["$active.$[n].energy","$active.0.energy"]
    }
  }
}

2

Answers


  1. Here’s one way you could do it.

    db.collection.aggregate([
      {
        "$project": {
          "Difference": {
            "$subtract": [
              {"$arrayElemAt": ["$Active.energy", 2]},
              {"$arrayElemAt": ["$Active.energy", 0]}
            ]
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
  2. Assume that the Active array can be of arbitrary length and we wish to get the difference between the greatest and least value of energy. Here’s a solution:

    db.foo.aggregate([
        // Ensure sorted ordering of array:                                          
        {$addFields: {
            'Active': {$sortArray: {'input':'$Active', 'sortBy': { energy: 1 }}}
        }}              
    
        // $arrayElemAt is 0-based, so need $size:'$Active' - 1:                     
        ,{$project: {
            'difference': {$subtract: [
                {$arrayElemAt:['$Active.energy', {$subtract:[{$size:'$Active'},1]} ]},
                {$arrayElemAt:['$Active.energy',0]} ] }
        }}
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search