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
Here’s one way you could do it.
Try it on mongoplayground.net.
Assume that the
Active
array can be of arbitrary length and we wish to get the difference between the greatest and least value ofenergy
. Here’s a solution: