Mongodb,带条件的$ sum

文件:

[
  {
    name: 'abc'
    length: 25,
    area: 10
  },
  {
    name: 'abc',
    length: 5
  }
]

汇总查询后的输出:

[
  {
     count: 2,
     summarizedLength: 30,
     summarizedArea: null,
     _id: {
       name: 'abc'
     }
  }
]

lengtharea应总结。但仅当所有文档都具有arealength属性时。

因此,如果length分组的属性缺少任何属性,则该summarizedLength值应为null/undefined/not exisitng,并且与相同area

我尝试了这个:

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

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

萨拉瓦那

来自Mongo文档$ sum行为

如果在包含数字值和非数字值的字段上使用,$ sum将忽略非数字值并返回数字值的总和。

如果用于集合中任何文档中都不存在的字段,则$ sum对该字段返回0。

如果所有操作数均为非数字,则$ sum返回0。

我们可以将$push所有面积和长度都排列成数组,并count与数组的长度进行比较

db.n.aggregate(

    [ 
        {
            $group: {
                _id: { name: "$name" }, 
                count: { $sum: 1 }, 
                area : {$push : "$area"}, 
                length : {$push : "$length"} } 
        },
        {
            $project:{
                _id: "$_id",
                count: "$count",
                summarizedLength: { $cond : [ {$eq : [ "$count", {$size : "$length"} ]} , { $sum : ["$length"] }, "not all numbers" ] },
                summarizedArea: { $cond : [ {$eq : [ "$count", {$size : "$area"} ]} , { $sum : ["$area"] }, "not all numbers" ] },
            }
        }
    ] 
)

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

如果区域和长度可能包含非数字数据,则要严格检查类型,而不是undefined我们可以$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"
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章