Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda