Mongodb,有条件的$ sum [英] Mongodb, $sum with condition
本文介绍了Mongodb,有条件的$ sum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
文档:
[
{
name: 'abc'
length: 25,
area: 10
},
{
name: 'abc',
length: 5
}
]
汇总查询后的输出:
[
{
count: 2,
summarizedLength: 30,
summarizedArea: null,
_id: {
name: 'abc'
}
}
]
应该总结length
和area
.但仅当所有文档都具有area
或length
属性时.
The length
and area
should summarized. But only if all documents have the area
or length
property.
因此,如果分组属性中缺少任何length
属性,则summarizedLength
值应为null/undefined/not exisitng
,并且与area
相同.
So if any length
property is missing by the grouped properties, the summarizedLength
value should be null/undefined/not exisitng
, and same with area
.
我尝试过:
let query = mongoose.model('mycollection').aggregate([
{
$group: {
_id: {
name: $name
},
count: {
$sum: 1
},
summarizedLength: { $sum: "$length" },
summarizedArea: { $sum: "$area" },
}
}
]);
问题是,如果缺少任何属性,我需要取消$sum
.这可能吗?
Problem is, I need to cancel the $sum
if any property is missing. Is this possible?
推荐答案
查看全文