How to Determine Average in MongoDB

02 / Apr / 2013 by Sakshi Tyagi 0 comments

MongoDB provides several ways of computing the average value of a group in a collection. One of the simplest ways of determining average is using the method

The method bunches the documents of a collection on the basis of the keys mentioned and executes aggregation functions on them. This method can be used for performing several operations, including count and addition. In order words, the method performs functionality similar to that of the SQL’s Select-Group By combination.

The implementation and working of the method for determining the average of a field in a collection is illustrated here using the example of a collection ‘userquestions’. The query, which can be used to find average, is as follows –

var reduceFunction = function(currentDocument, previousDocument) {
     previousDocument.totalRating += currentDocument.rating; previousDocument.count += 1

var finalizeFunction = function(currentDocument) {
     currentDocument.average = currentDocument.totalRating/currentDocument.count;
     delete currentDocument.totalRating;
     delete currentDocument.count;
     key: {'quesId': true},
     initial: {totalRating: 0, count:0},
     reduce: reduceFunction,

In the present context, the value of the ‘key’ is the field ‘quesId’. Documents are grouped together on the basis of this key. The initial values for the parameters ‘count’ and ‘totalRating’ are set to zero. Besides these, two functions are declared and defined in the query. The function reduce totals the value of the ‘rating’ and saves it in ‘totalRating’. In addition to this, it also maintains the count of documents processed.

On the other hand, the function ‘finalize’ determines the average value of rating by dividing the value of ‘totalRating’ by the count.The execution of this query returns an array containing different ‘quesId’, which represents the different groups and the corresponding average rating for each of these groups.

Hope this will help. :-)

Sakshi Tyagi


Leave a comment -