Mongodb mongoose聚合和求和嵌套对象(非数组)字段

Mongodb mongoose聚合和求和嵌套对象(非数组)字段,mongodb,mongoose,sum,aggregate,Mongodb,Mongoose,Sum,Aggregate,我已经看到很多帖子使用aggregate到sum嵌套ARRAY字段,我尝试将其用于我的嵌套对象,但没有成功 当我查询时,数据结构类似于 [ { "key": "value", "more_key": "more_value", "meals": { "A": { "name": "salmon",

我已经看到很多帖子使用
aggregate
sum
嵌套
ARRAY
字段,我尝试将其用于我的嵌套对象,但没有成功

当我查询时,数据结构类似于

[
        {
            "key": "value",
            "more_key": "more_value",
            "meals": {
                "A": {
                    "name": "salmon",
                    "amount": "8"
                },
                "B": {
                    "name": "vege",
                    "amount": "6"
                },
            }
        },
        {
            "key": "value",
            "more_key": "more_value",
            "meals": {
                "A": {
                    "name": "salmon",
                    "amount": "8"
                },
                "B": {
                    "name": "vege",
                    "amount": "6"
                },
                "C": {
                    "name": "other meal",
                    "amount": "6"
                },
            }
        },
    ];
我正在尝试对
金额进行求和

我试过这样的东西

await Model.aggregate([
        { $match: { isDeleted: false } },
        { $unwind: '$meals' },  // tried with + without this
        { $group: { _id: null, sum: { $sumA: '$meals.A.amount', $sumB: '$meals.B.amount' } } }
    ]);
有人能给我一些建议和建议如何做到这一点吗


提前感谢。

这里有几件事:

1)
$unwind
不适用于对象,仅适用于数组。您可以通过使用
$objectToArray

2) 您的金额字段看起来像是字符串类型,因此需要将其转换为数字进行求和

下面是一个聚合,它可以满足您的需要:

await Model.aggregate([
  // Convert meals object to array
  { $project: { meals: { $objectToArray: '$meals' }}},

  //  unwind meals array
  { $unwind:  '$meals' },

  // convert meals.v.amount to integer and sum them (the v is shorthand for values)
  { $group: { 
    _id: null, 
    total: {
      $sum: { 
        $convert: {
          input: '$meals.v.amount',
          to: 'int'
        }
      }
    }
  }}
])

您可以将$group的_id更改为
\u id:fines.k
以按用餐对象的键(即A、B、C)求和

我想
{$unwind:{'$fines'}},
表示
{$unwind:'$fines'},
对吗?但是我得到了
未处理PromiserEjectionWarning:MongoError:无法识别的表达式“$convert”
$convert在MongoDB的4.0版中是新的,但它已经过时一年左右了。您使用的是什么版本?如果出于任何原因无法更新到版本4.x,请参阅本文,了解如何在早期版本中将字符串转换为int:啊!难怪我用
$convert
$toInt
四处搜索,每个人都在建议,刚才检查提供的沙盒使用的是mongodb 3.6x>。mongodb在不同版本之间似乎变化很大,所以可能有点令人沮丧!正确,代码正在覆盖集合中的数据以更改类型。