Looking for MongoDB developers?
Contact Us

How to calculate average & sum of a field using Mongo | Ruby

How to calculate average and sum of a field with filters using mongo in ruby. We talk about two queries in mongo to calculate average and sum for a given field with option to add filtering of data.

Posted by Ameena on 15 Jan 2018
How to calculate average & sum of a field using Mongo | Ruby

MongoDB is an open source database that uses a document-oriented data model. Instead of using tables and rows as in relational databases, MongoDB is built on an architecture of collections and documents.

Basic setup of mongo

require 'mongo'

Mongo::Client.new(
        [ $configuration["database_end_point"] ],
        :database => $configuration["database_name"]
      )

Average

response = mongo[:collection].aggregate([
          {
            "$match" => {
              "a" => 1,
              "b" => { "$ne" => nil, "$exists" => true }
            },
          },
          {
            "$group" => {
              "_id" => "$a",
              "avg" => { "$avg" => "$b" }
            }
          }
        ]).to_a[0]
        response ? response["avg"] : 0

Sum

response = mongo[:collection].aggregate([
          {
            "$match" => {
              "a" => 1,
              "b" => { "$ne" => nil, "$exists" => true }
            },
          },
          {
            "$group" => {
              "_id" => "$a",
              "sum" => { "$sum" => "$b" }
            }
          }
        ]).to_a[0]
        response ? response["sum"] : 0

keep Coding !!!

Ameena


Looking for MongoDB developers?
Contact Us

Related Services.



Hire ReactJS Developers
Hire Gatsby Developers
Hire NextJS Developers

We support the Open Source community.



Have a Project in mind?