Sum data from other collection

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({
			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([{
					from: 'BusinessPlans',
					localField: 'farmerId',
					foreignField: 'id',
					as: 'totalFieldSize'

What am I doing wrong?

Thanks in advanced, Yaakov.

May be it is simply a typing error.

In the JS loop, you have BusinessPlan without terminal s and in aggregation you use BusinessPlans with a terminal s.

Thanks @steevej
I expected to get error messages on wrong ids. Now I know :slight_smile:

1 Like