gpt4 book ai didi

Mongodb,带条件的$sum

转载 作者:可可西里 更新时间:2023-11-01 10:02:12 25 4
gpt4 key购买 nike

文件:

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

聚合查询后的输出:

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

长度面积应该总结。但前提是所有文档都具有 arealength 属性。

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

我试过这个:

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

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

最佳答案

来自 Mongo 文档 $sum behavior

If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values.

If used on a field that does not exist in any document in the collection, $sum returns 0 for that field.

If all operands are non-numeric, $sum returns 0.

我们可以$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" ] },
}
}
]
)

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

要严格检查类型,以防 area 和 length 可能包含非数字数据,而不是 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"
}

关于Mongodb,带条件的$sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48235279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com