[SERVER-6275] $avg assume 0 for undefined Created: 02/Jul/12  Updated: 11/Jul/16  Resolved: 27/Jul/12

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: 2.1.2
Fix Version/s: 2.2.0-rc1

Type: Bug Priority: Major - P3
Reporter: Adam Bell Assignee: Matt Dannenberg
Resolution: Done Votes: 0
Labels: $avg, aggregation
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Macbook Pro (early 2011) OSX 10.7.4


Operating System: ALL
Participants:

 Description   

$avg assumes 0 for undefined $avg should behave like $push and $addToSet and return nothing for undefined



 Comments   
Comment by auto [ 01/Aug/12 ]

Author:

{u'date': u'2012-07-27T15:11:03-07:00', u'email': u'aaron@10gen.com', u'name': u'Aaron'}

Message: SERVER-6551 was fixed by SERVER-6275 changes. Update tests to reflect new behavior.
Branch: master
https://github.com/mongodb/mongo/commit/ac2f2b228f12a3a541639e34cd4d8df62bf31351

Comment by auto [ 27/Jul/12 ]

Author:

{u'date': u'2012-07-23T14:27:55-07:00', u'email': u'dannenberg.matt@gmail.com', u'name': u'Matt Dannenberg'}

Message: SERVER-6275 SERVER-6197 use double for $avg

also do not count non-numeric types in $avg
also part of SERVER-6166 up convert from int to long on $sum
Branch: master
https://github.com/mongodb/mongo/commit/186c5a411c3a1e616f7e876820a13af46d6faa4c

Comment by Adam Bell [ 24/Jul/12 ]

You are correct. Missing values should not affect average however in the version I have listed below they do affect the average.

Here is a test. Based on the functionality you described below the average here should be 10 not 7.5

db.avgtest.find()

{ "_id" : ObjectId("500e09d68df5ba3913f3f8f0"), "value" : 10 } { "_id" : ObjectId("500e09d98df5ba3913f3f8f1"), "value" : 10 } { "_id" : ObjectId("500e09db8df5ba3913f3f8f2"), "value" : 10 } { "_id" : ObjectId("500e09e48df5ba3913f3f8f3"), "name" : "No Value" }

> db.avgtest.aggregate({$project:{value:1}}, {$group:{_id:

{"key":1}

, avg:{$avg:"$value"}}})
{ "result" : [ { "_id" : { }, "avg" : 7.5 } ], "ok" : 1 }
> version()
version: 2.1.2

mongod --version
db version v2.1.2, pdfile version 4.5
Mon Jul 23 22:49:06 git version: 927beb54fb5ec38ccd0ca5fa712564a0696c9003

Let me know if there is any additional information I can provide or perhaps I am looking at this incorrectly.

Comment by Mathias Stearn [ 23/Jul/12 ]

missing values shouldn't effect average. If you want missing treated as 0 you can always do {avg: {$avg:{$ifNull:['$field', 0]}}}

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