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"
}
}