Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: 20contains values [60, 50], average = 55 - Group with
seq: 10contains values [-Infinity, 50], average = -Infinity - Any arithmetic operation with
-Infinityresults 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.
Advertisements
