[DOCS-8996] $avg aggregation operator should return null instead of 0 Created: 28/Sep/16  Updated: 30/Oct/23  Resolved: 02/Aug/17

Status: Closed
Project: Documentation
Component/s: Server
Affects Version/s: None
Fix Version/s: Server_Docs_20231030

Type: Task Priority: Major - P3
Reporter: Emily Hall Assignee: Allison Reinheimer Moore
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Documented
documents SERVER-14691 $avg aggregation operator should retu... Closed
Participants:
Days since reply: 7 years, 20 weeks ago
Epic Link: 3.4 Agg/Arrays

 Description   

Currently, if you run $avg against a (nonexistent) field, the return will be 0, instead of null. If you do $min or $max, you will get a null. The reason $avg and $sum should behave this way is so that when you do two pipeline $group operators in a row, currently $avg does not behave the same in both pipelines because the first $group stage will return a 0 instead of null for records that don't have the $group _id.

For example, imagine the records

{'a' : 1, 'b' : 1, 'value' : 1}
{'a' : 1, 'b' : 1, 'value' : 9}
{'a' : 1, 'b' : 2}

then if I run

db.test.aggregate({$group : {'_id' : {'a' : '$a', 'b' : '$b'}, 'average' : {'$avg' : '$value'}}}, {$group : {'_id' : {'a' : '$_id.a'}, 'average' : {'$avg' : '$average'}}});

I get 2.5 instead of 5, of course because the first $avg operation returns 0. If, however, this operation returned NULL, then it would work fine. Also, if this type of behavior is DESIRED, a simple ifnull() could always be used. However, I am of the opinion that $avg of a bunch of nulls is NULL, not 0.

I suppose the $sum operation returning 0 instead of null is of less consequence, but it should probably behave the same way.

Thoughts?


Generated at Thu Feb 08 07:57:23 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.