使用 $sum 计算对象中的总值,mongoose/mongodb

Using $sum to calculate the total value in a object, mongoose/mongodb

我有这个:

var actions = [
  project: 23123,
  title: 'Change of windows
  energySaving: {
      electricity: {
        lighting: 24324,
        equipment: 23423,
        fans: 234234,
        distribution: 234324,
        chiller: 234234,
        other: 234324
      },
      heating: {
        ventilation: 234324,
        shell: 23423,
        tapWater: 23423
      },
  }
]);

这是我从操作集合中获取一些字段的查询:

mongoose.model('Action').find({project: project._id})
  .select('title description energySaving')

      .exec(function(err, actions){
      res.status(200).send(actions);
    });
  })

我不想获取整个 "energySaving" 属性,而是想将其替换为 "totalEnergySaving",它是所有子对象的总和。是否可以使用聚合来做到这一点?如果是这样,则可能是 $sum 功能。不太确定如何。

由于您具有任意字段名称,因此使用当前架构设计实现聚合将非常困难。为了执行大多数类型的查询和操作,您需要重新设计架构来存储数据,如下所示:

{
    "_id" : ObjectId("54f46f18c36dcc206d0cec38"),
    "project" : 23123,
    "title" : "Change of windows",
    "energySaving" : [ 
        {
            "energy" : "electricity",
            "type" : "lighting",
            "value" : 24324
        }, 
        {
            "energy" : "electricity",
            "type" : "equipment",
            "value" : 24324
        }, 
        {
            "energy" : "electricity",
            "type" : "fans",
            "value" : 24324
        }, 
        {
            "energy" : "electricity",
            "type" : "distribution",
            "value" : 24324
        }, 
        {
            "energy" : "electricity",
            "type" : "chiller",
            "value" : 24324
        }, 
        {
            "energy" : "electricity",
            "type" : "other",
            "value" : 24324
        }, 
        {
            "energy" : "heating",
            "type" : "ventilation",
            "value" : 24324
        }, 
        {
            "energy" : "heating",
            "type" : "shell",
            "value" : 24324
        }, 
        {
            "energy" : "heating",
            "type" : "tapWater",
            "value" : 24324
        }
    ]
}

然后您可以汇总得到最终的 titledescriptiontotalEnergySaving,如下所示:

db.collection.aggregate( [
    { $unwind: "$energySaving" },
    { 
       $group: {
          _id: {
             title: '$title',
             description: '$description' 
          },
          totalEnergySaving: { $sum: '$energySaving.value' } 
       } 
    },
    {
        $project: {
            _id: 0,
            title: '$_id.title',
            description: '$_id.description',
            totalEnergySaving: 1
        }
    }
]);

结果:

{
    "result" : [ 
        {
            "totalEnergySaving" : 218916,
            "title" : "Change of windows",
            "description" : "Detailed breakdown of energy savings"
        }
    ],
    "ok" : 1
}