Mongodb,$sum带条件

Mongodb,$sum带条件,mongodb,aggregation-framework,Mongodb,Aggregation Framework,文件: [ { name: 'abc' length: 25, area: 10 }, { name: 'abc', length: 5 } ] 聚合查询后的输出: [ { count: 2, summarizedLength: 30, summarizedArea: null, _id: { name: 'abc' } } ] 应总结长度和区域。但仅当所有文档都具

文件:

[
  {
    name: 'abc'
    length: 25,
    area: 10
  },
  {
    name: 'abc',
    length: 5
  }
]
聚合查询后的输出:

[
  {
     count: 2,
     summarizedLength: 30,
     summarizedArea: null,
     _id: {
       name: 'abc'
     }
  }
]
应总结
长度
区域
。但仅当所有文档都具有
区域
长度
属性时

因此,如果分组属性缺少任何
length
属性,则
summaredLength
值应为
null/未定义/不存在
,与
区域
相同

我试过这个:

let query = mongoose.model('mycollection').aggregate([
    {
      $group: {
        _id: {
          name: $name
        },
        count: {
          $sum: 1
        },
        summarizedLength: { $sum: "$length" },
        summarizedArea: { $sum: "$area" },
      }
    }
  ]);

问题是,如果缺少任何属性,我需要取消
$sum
。这可能吗?

来自Mongo文档

如果用于同时包含数值和非数值的字段, $sum忽略非数值并返回数值的和 价值观

如果在中的任何文档中不存在的字段上使用 集合$sum为该字段返回0

如果所有操作数都是非数字的,$sum返回0

我们可以
$push
将所有面积和长度推送到数组,并将
计数
与数组长度进行比较

骨料(

或者,我们可以计算定义的
长度和面积的数量,以及总数
计数
,如果计数匹配,则所有数字都是未定义的

为了严格检查类型,如果面积和长度可能包含非数字数据,我们可以进行
$type
检查,而不是
未定义

db.n.aggregate(
    [
        {
            $group: {
                _id: { name: "$name" },
                count: { $sum: 1 },
                areaCount : { $sum : { $cond : [ {$eq : [ "$area", undefined ]} , 0, 1 ] } },
                lengthCount : { $sum : { $cond : [ {$eq : [ "$length", undefined ]} , 0, 1 ] } },
                summarizedLength: { $sum: "$length"  },
                summarizedArea: { $sum: "$area"  }
            }
        },
        {
            $project : {
                _id : "$_id",
                count: "$count",
                summarizedLength: { $cond : [ {$eq : [ "$count", "$lengthCount" ]} , "$summarizedLength", "not all numbers" ] },
                summarizedArea: { $cond : [ {$eq : [ "$count", "$areaCount" ]} , "$summarizedArea", "not all numbers" ] },
            }
        }
    ]
).pretty()
输出

{
    "_id" : {
        "name" : "abc"
    },
    "count" : 2,
    "summarizedLength" : 30,
    "summarizedArea" : "not all numbers"
}
{
    "_id" : {
        "name" : "abc"
    },
    "count" : 2,
    "summarizedLength" : 30,
    "summarizedArea" : "not all numbers"
}