[SERVER-14691] $avg aggregation operator should return null instead of 0 Created: 25/Jul/14  Updated: 08/Aug/17  Resolved: 15/Jul/15

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: 3.1.6

Type: Improvement Priority: Major - P3
Reporter: Ben Rotz Assignee: Charlie Swanson
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Documented
is documented by DOCS-8996 $avg aggregation operator should retu... Closed
Related
is related to SERVER-30270 $sum should be null when no fields/no... Closed
is related to SERVER-27422 Agg Pipeline return none type on from... Closed
Backwards Compatibility: Major Change
Sprint: Quint Iteration 4, Quint Iteration 5, Quint Iteration 6
Participants:

 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?



 Comments   
Comment by Githook User [ 15/Jul/15 ]

Author:

{u'username': u'cswanson310', u'name': u'Charlie Swanson', u'email': u'charlie.swanson@mongodb.com'}

Message: SERVER-14691: $avg accumulator should return null if it receives no numeric inputs
Branch: master
https://github.com/mongodb/mongo/commit/84699e46bf32a2c9a17e85526bcc9c8395f64ac6

Generated at Thu Feb 08 03:35:40 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.