来自蒙戈文档$sum 行为 https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#non-numeric-or-non-existent-fields
如果用于同时包含数字值和非数字值的字段,
$sum 忽略非数字值并返回数字的总和
价值观。
如果用于任何文档中不存在的字段
集合,$sum 对该字段返回 0。
如果所有操作数都是非数字,则 $sum 返回 0。
we can $push
所有面积和长度到数组,并比较count
与数组的长度
db.n.聚合(
[
{
$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
长度和面积以及总面积count
,如果计数匹配,则所有数字其他数字未定义。
要严格检查类型,以防面积和长度可能包含非数字数据,而不是undefined
我们可以做的$type
check
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()
output
{
"_id" : {
"name" : "abc"
},
"count" : 2,
"summarizedLength" : 30,
"summarizedArea" : "not all numbers"
}