In this example, we are going to calculate the average rating each author received for his or her articles—published within the last 24 hours—using the group()
method. We are going to execute this method within a PHP program. The program will output a HTML table, displaying the total number of articles and average rating for each author:
1. Open up your text editor and create a new PHP script named
avg_rating.php
. Put the following code in it:<?php require('dbconnection.php'); $mongo = DBConnection::instantiate(); $collection = $mongo->getCollection('sample_articles'); $key = array('author' => 1); //set both the aggregation counter and total rating to zero $initial = array('count' => 0, 'total_rating' => 0); //reduce function, increases counter by 1 and adds up the ratings $reduce = "function(obj, counter) { counter.count++;". "counter.total_rating += obj.rating;}"; //finalize function, finds the average rating...