I’m new to MongoDb.
I need to calculate sum for each document using another collection.
Inefficient way will be:
const farmers = await Farmer.find();
for (let Farmers of farmers) {
let farmerBusineesPlans = await BusinessPlan.find({
farmerId: Farmers.id
});
for (let BusinessPlan of farmerBusineesPlans) {
totalBusinessPlansSize =
totalBusinessPlansSize + BusinessPlan.totalFieldSize;
}
Farmers.totalBusinessPlansSize = totalBusinessPlansSize;
totalBusinessPlansSize = 0;
}
I tried to aggregate like the following code, but I get an empty array in the “totalFieldSize” field.
const farmers = await Farmer.aggregate([{
$lookup:
{
from: 'BusinessPlans',
localField: 'farmerId',
foreignField: 'id',
as: 'totalFieldSize'
}
}]);
What am I doing wrong?
Thanks in advanced, Yaakov.