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