The Traveling Coder
The Traveling Coder

Reputation: 311

Sum column, between dates fields in Mongoose

I am trying to learn mongoose, I come from a SQL background and I am having difficulties figuring out how this works.

So I am essentially trying to run this SQL code in Mongoose

$sql = "SELECT SUM(comdataPurchase)
              FROM fuel566243
              WHERE fuelDate BETWEEN '$startDate' AND '$endDate';";

But I cannot get it to work properly for me in mongoose. Here is what I have so far.

FuelReceipt.aggregate([{$match:{date:{$gte: fuelStart, $lt: fuelEnd}}},
                {$group:{truckNumber: truckNumber, dieselGallons:{'$sum': '$count'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    console.log(data);
                });

Thank you in advance for your help <3

edit:-------------

This works:

FuelReceipt.aggregate([
                {$group:{_id: '$truckNumber', 
                         dieselGallons:{$sum: '$dieselGallons'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    console.log(JSON.stringify(data, null));
                });

This gives empty array:

FuelReceipt.aggregate([
                {$match:{date:{$gte: fuelStart, $lte: fuelEnd}}},
                {$group:{_id: '$truckNumber', 
                         dieselGallons:{$sum: '$dieselGallons'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    console.log(JSON.stringify(data, null));
                });

edit 2:----------------

I figured it out, had to change the data type for the start and end dates.

FuelReceipt.aggregate([
                {$match:{date:{$gte: new Date(fuelStart), $lte: new Date(fuelEnd)}}},
                {$group:{_id: '$truckNumber', 
                         fuelCost:{$sum: '$fuelCost'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    res.send(data);
                    console.log(JSON.stringify(data, null));
                });

Upvotes: 1

Views: 109

Answers (1)

mickl
mickl

Reputation: 49975

The "between" part is implemented correctly however $group requires _id value. You can set it to null if you want to get single aggregate for entire set of documents:

{$group: { _id: null, dieselGallons: {'$sum': '$comdataPurchase'}}}

Upvotes: 1

Related Questions