Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-6197

$avg is calculated using integer math for integers even though result value is of type double

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 2.2.0-rc1
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • None

      Observed behavior: $avg on integers is calculated using integer addition and division, as a result of which the average of ( 1, 1, 1, ..., 1, 0 ) is 0 and is reported as the double value 0.0.
      Expected behavior: $avg is computed and reported using double values.

      Test:

      c = db.c;
      c.drop();
      
      // Insert 1000 one values and 1 zero value.
      for( i = 0; i < 1000; ++i ) {
          c.save( { a:NumberInt( 1 ) } );
      }
      c.save( { a:NumberInt( 0 ) } );
      
      // The average is currently reported as 0.0.
      printjson( c.aggregate( { $group:{ _id:0, avg:{ $avg:'$a' } } } ) );
      

      There is also some seemingly arbitrary overflow behavior, for example two ints will overflow on a shard but not on a standalone mongod.

            Assignee:
            matt.dannenberg Matt Dannenberg
            Reporter:
            aaron Aaron Staple
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: