简体   繁体   中英

MongoDB aggregation : Group by Category and sum up the amount

I have the following structure in my collection (you don't have to mind the status) :

{
    "_id": {
        "$oid": "5e6355e71b14ee00175698cb"
    },
    "finance": {
        "expenditure": [
            {
                "status": true,
                "_id": { "$oid": "5e63562d1b14ee00175698df" },
                "amount": { "$numberInt": "100" },
                "category": "Sport"
            },
            {
                "status": true,
                "_id": { "$oid": "5e6356491b14ee00175698e0" },
                "amount": { "$numberInt": "200" },
                "category": "Sport"
            },
            {
                "status": true,
                "_id": { "$oid": "5e63565b1b14ee00175698e1" },
                "amount": { "$numberInt": "50" },
                "category": "Outdoor"
            },
            {
                "status": true,
                "_id": { "$oid": "5e63566d1b14ee00175698e2" },
                "amount": { "$numberInt": "400" },
                "category": "Outdoor"
            }
        ]
    }
}

My previos command was this:

User.aggregate([
    { $match: {_id: req.user._id} },
    { $unwind: '$finance.expenditure' },
    { $match: {'finance.expenditure.status': true} },
    { $sort: {'finance.expenditure.currentdate': -1} },
    {
        $group: {
            _id: '$_id',
            expenditure: { $push: '$finance.expenditure' }
        }
    }
])

With this I just get every single expenditure back.

But now I want to group the expenditures by their category and sum up the amount of every single expenditure for their group.

So it should look like this:

{ "amount": 300 }, "category": "Sport" },
{ "amount": 450 }, "category": "Outdoor" }

Thanks for your help

Instead of grouping on _id field group on category field & sum amount field:

db.collection.aggregate([
  { $match: {_id: req.user._id}},
  {
    $unwind: "$finance.expenditure"
  },
  {
    $match: {
      "finance.expenditure.status": true
    }
  },
  {
    $sort: {
      "finance.expenditure.currentdate": -1
    }
  },
  {
    $group: {
      _id: "$finance.expenditure.category",
      amount: {
        $sum: "$finance.expenditure.amount"
      }
    }
  },
  {
    $project: {
      _id: 0,
      category: "$_id",
      amount: 1
    }
  }
])

Test : MongoDB-Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM