O'Reilly logo

PHP and MongoDB Web Development by Rubayeet Islam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action - calculating the average rating per author

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required