Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Calculate average with mongoose using aggregate framework

I am struggling to solve this problem. I use mongoose in a Node.js backend and need to find the average of a field in a big dataset. There are around 1.500.000 documents in the db, which is why I tried to use the model.aggregate() function:

const vxxEntry = require("../model/vxxEntry");

const getAvg = async function () {
    return vxxEntry.aggregate([
            {
                $group: {
                    _id: null,
                    avgVolume: {$avg: "$volume"}
                }
            },
        ],
        {
            allowDiskUse: true
        }
    )
}

The model looks like this:

const mongoose = require("mongoose");
const {Decimal128} = require("mongodb");

const vxxEntrySchema = new mongoose.Schema({
    timestamp: { type: Date},
    price: { type: Decimal128},
    volume: { type: Number},
    exchange: { type: String},
});

module.exports = mongoose.model("vxxEntry", vxxEntrySchema);

The problem is that the function getAvg() always returns:

[ { _id: null, avgVolume: null } ]

Thankful for any solutions!

Edit

The same happens when I run the query in the native mongo shell!

Running the following returns a big array of objects so I think the collection and the field do exist.

{
    $group: {
        _id: "$volume"
    }
}

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!