【问题标题】:MongoDB aggregation : Group by Category and sum up the amountMongoDB聚合:按类别分组并总结金额
【发布时间】:2024-04-27 06:00:01
【问题描述】:

我的收藏中有以下结构(您不必介意状态):

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

感谢您的帮助

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework mongo-shell


    【解决方案1】:

    而不是在类别字段和总金额字段上对_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

    【讨论】: