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}`)

    })

});



About Simbla

Trying to create a website for their own business, Simbla's founders recognized, over the years, a lack of excellent, simple tools available on the market. Therefore, in 2013 Simbla was founded, for the purpose of providing a smart and easy website building solution for all types of businesses. Simbla's founders have more than 15 years of experience with web-based platforms and website building. We are helping SMB's to create a web presence and to evolve easily into a highly competitive market.

In our vision Simbla creates a new environment where websites are meant for everybody!

Social

all rights reserved to simbla inc

2016