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.
$matchthat filters on{date: {$gte: new Date('2017-12-01T00:00:00Z')}}and run your$groupas the second stage. For the current month, substitute the12in the date string withnew Date.getMonth() + 1. You need to add 1 togetMonthbecause it is zero-based. (Also see stackoverflow.com/questions/31071999/date-comparison-in-mongodb for a date comparison discussion).var date = new Date(); var compare = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0)aggregatearray.$matchas the first stage,$groupas the second. Glad I could help. Best of luck.