子文档的 MongoDB $sum 和 $avg [英] MongoDB $sum and $avg of sub documents
本文介绍了子文档的 MongoDB $sum 和 $avg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要得到 $sum 和 $avg 的子文档,我想得到 $sum 和 $avg 的 Channels[0].. 和其他频道.我的数据结构是这样的
I need to get $sum and $avg of subdocuments, i would like to get $sum and $avg of Channels[0].. and other channels as well. my data structure looks like this
{
_id : ... Location : 1,
Channels : [
{ _id: ...,
Value: 25
},
{
_id: ... ,
Value: 39
},
{
_id: ..,
Value: 12
}
]
}
推荐答案
解决方案 1:基于此示例使用两个组:上一个问题
Solution 1: Using two groups based this example: previous question
db.records.aggregate(
[
{ $unwind: "$Channels" },
{ $group: {
_id: {
"loc" : "$Location",
"cId" : "$Channels.Id"
},
"value" : {$sum : "$Channels.Value" },
"average" : {$avg : "$Channels.Value"},
"maximun" : {$max : "$Channels.Value"},
"minimum" : {$min : "$Channels.Value"}
}},
{ $group: {
_id : "$_id.loc",
"ChannelsSumary" : { $push :
{ "channelId" : '$_id.cId',
"value" :'$value',
"average" : '$average',
"maximun" : '$maximun',
"minimum" : '$minimum'
}}
}
}
]
)
解决方案 2:有一个属性我没有在我的原始问题上显示,这可能有助于独立于Channels._Id"的Channels.Id"
Solution 2: there is property i didn't show on my original question that might of help "Channels.Id" independent from "Channels._Id"
db.records.aggregate( [
{
"$unwind" : "$Channels"
},
{
"$group" : {
"_id" : "$Channels.Id",
"documentSum" : { "$sum" : "$Channels.Value" },
"documentAvg" : { "$avg" : "$Channels.Value" }
}
}
] )
这篇关于子文档的 MongoDB $sum 和 $avg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文