How to get a "-Infinity" result for $avg in an aggregate query?

In MongoDB aggregation, the $avg operator returns -Infinity when calculating the average of values that include -Infinity. This occurs because any arithmetic operation involving -Infinity propagates the infinite value.

Syntax

db.collection.aggregate([
    {
        $group: {
            "_id": "$groupField",
            "average": { $avg: "$numericField" }
        }
    }
]);

Sample Data

db.demo5.insertMany([
    { "_id": 100, "seq": 10, "Value": -Infinity },
    { "_id": 101, "seq": 10, "Value": 50 },
    { "_id": 102, "seq": 20, "Value": 60 },
    { "_id": 103, "seq": 20, "Value": 50 }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 100,
        "1": 101,
        "2": 102,
        "3": 103
    }
}

View Sample Data

db.demo5.find();
{ "_id": 100, "seq": 10, "Value": -Infinity }
{ "_id": 101, "seq": 10, "Value": 50 }
{ "_id": 102, "seq": 20, "Value": 60 }
{ "_id": 103, "seq": 20, "Value": 50 }

Example: Aggregate with $avg

Calculate the average Value grouped by seq field ?

db.demo5.aggregate([
    {
        $group: {
            "_id": "$seq",
            "average": { $avg: "$Value" }
        }
    }
]);
{ "_id": 20, "average": 55 }
{ "_id": 10, "average": -Infinity }

How It Works

  • Group with seq: 20 contains values [60, 50], average = 55
  • Group with seq: 10 contains values [-Infinity, 50], average = -Infinity
  • Any arithmetic operation with -Infinity results in -Infinity

Conclusion

The $avg operator returns -Infinity when any value in the group is -Infinity. This mathematical behavior ensures that infinite values propagate through calculations as expected in MongoDB aggregation pipelines.

Updated on: 2026-03-15T02:25:57+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements