簡體   English   中英

MongoDB 聚合:按類別分組並匯總數量

[英]MongoDB aggregation : Group by Category and sum up the amount

我的收藏中有以下結構(您不必介意狀態):

{
    "_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"
            }
        ]
    }
}

我以前的命令是這樣的:

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' }
        }
    }
])

有了這個,我就可以收回每一筆支出。

但是現在我想按類別對支出進行分組,並總結出他們所在組的每項支出的金額。

所以它應該是這樣的:

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

謝謝你的幫助

而不是在類別字段和總金額字段上的_id字段組上分組:

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
    }
  }
])

測試: MongoDB-Playground

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM