1

I have collection named transactions in Mongodb which stores the expenses or income along with bank details and date. I want to show the total expenses for current month. For example, if I am storing 3 transactions having 3 expenses each of $10 $20 for month of December and $20 for the month of November, I should get the output as $30. I have stored the date as the ISO date object. How should I compare the months in the database with the current month in the aggregate function of mongodb. Following is the code I am trying to get the total expenses for the current month : result = await transactionCollection.aggregate([{ $group : { _id : {trans_type : "$transaction_type"}, amount : {$sum : "$amount"} } }, { $match : {date.getMonth() : new Date().getMonth()} }]).toArray()

Any tips or suggestions are deeply appreciated.

  • If you only want expenses for the current calendar month, e.g., December, begin your aggregation with a `$match` that filters on `{date: {$gte: new Date('2017-12-01T00:00:00Z')}}` and run your `$group` as the second stage. For the current month, substitute the `12` in the date string with `new Date.getMonth() + 1`. You need to add 1 to `getMonth` because it is zero-based. (Also see https://stackoverflow.com/questions/31071999/date-comparison-in-mongodb for a date comparison discussion). – t.888 Dec 14 '17 at 01:39
  • This should work as a way to construct a date object for the current month: `var date = new Date(); var compare = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0)` – t.888 Dec 14 '17 at 01:46
  • 1
    thanks a lot for your reply. can you please let me know what is the second stage you were talking about? also what does the compare variable is used for? how should I put the current month in the $match query object instead of writing the complete date manually. – Shreyas Sule Dec 14 '17 at 02:01
  • 1
    Yes that works. Thanks a lot for your help – Shreyas Sule Dec 14 '17 at 02:17
  • By stages I just mean the items passed to the `aggregate` array. `$match` as the first stage, `$group` as the second. Glad I could help. Best of luck. – t.888 Dec 14 '17 at 04:56

0 Answers0