Javascript Aggregate Functions

In the next example we will learn how to use aggregate functions such as average, minimum, sum.

We will be using two tables:


 Table 1 - Restaurants (Name).

 Table 2 - Rating ( RestaurantId,  Score)

 

Example:

var query = new Simbla.Query("Rating")


// Get rating form the last year

var date = new Date();

date.setFullYear(date.getFullYear() - 1)

query.greaterThan("createdAt", date)


// The first parameter is the group by field.

// In the example we will group by the "FieldName.TableName.FieldValue"

 // The second parameter is the group function.

// in this example we will get the avg (Average) of the "Score" field.

  

 // Other functions available for the group function are sum, min, max. for count the total number of rows you can use {sum: 1}

  



query.aggregate("RestaurantId.Restaurants.Name", { avg: "Score" }).then(function (e) {

    e.results.forEach(function (r) {

        console.log(`Name: ${r._id}. Average score: ${r.value}`)

    })

});


// example for other group by functions


query.aggregate("RestaurantId.Restaurants.Name", { max: "Score" }).then(function (e) {

    e.results.forEach(function (r) {

        console.log(`Name: ${r._id}. Max score: ${r.value}`)

    })

});



query.aggregate("RestaurantId.Restaurants.Name", { sum: "Score" }).then(function (e) {

    e.results.forEach(function (r) {

        console.log(`Name: ${r._id}. Total score: ${r.value}`)

    })

});



query.aggregate("RestaurantId.Restaurants.Name", { sum: 1 }).then(function (e) {

    e.results.forEach(function (r) {

        console.log(`Name: ${r._id}. Total votes: ${r.value}`)

    })

});