MongoDB $ sum和$ avg子文档 [英] MongoDB $sum and $avg of sub documents

查看:297
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆