Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda