Mongoose Aggregation Example (grouping, sum and projection)

JS
S
JavaScript

Example on MongoDB using match, group (with sum directive) and project pipeline operators.

1  const begOfMonth = new moment(date).utc().startOf('month').toDate();
2  const endOfMonth = new moment(date).utc().endOf('month').toDate();
3
4  return FinanceModel.aggregate()
5    .match({ 
6      amount: { $lt: 0 },
7      date: { $gte: begOfMonth, $lte: endOfMonth }
8    })
9    .group({
10      _id: "$category",
11      total: { $sum: "$amount"  }
12    })
13    .project({
14        category:'$_id', total:1, _id:0
15    })    
16    .exec()

Created on 8/4/2018