如何使用mongo获取元素总和?

时间:2014-12-05 12:58:28

标签: mongodb

我有以下json结构 -

[{
 cName:"A",
"vms" : [ 
    {
        "status":"off",
        "name":"ds0",
        "capacity":5
    }, 
    {
        "name" : "ds1",
         "status":"on",
         "capacity":5
    }, 
    {
        "name" : "ds2",
         "status":"off",
          "capacity":5
    }, 
    {
        "name" : "ds3",
         "status":"off",
                 "capacity":10
    }
    ],
},
{
 cName:"B",
"vms" : [ 
    {
        "name" : "ds4",
         "status":"on",
                 "capacity":52
    }, 
    {
        "name" : "ds3",
         "status":"off",
         "capacity":50
    }, 
    {
        "name" : "ds5",
         "status":"off",
                 "capacity":15
    }
    ],
}
]

我的预期输出如下 -

[{
"cName":"A",
"capacity":20,
},[{
"cName":"B",
"capacity":65,
}
]

我使用mongo聚合来获取输出。

我能够使用它获得cname和容量但无法获得容量总和。

如何使用mongo聚合获得vms的容量总和?

1 个答案:

答案 0 :(得分:0)

如果我理解正确

db.f.aggregate([
{
    $unwind:"$vms"
},

{
    $group:{
        _id:"$cName",
        capacity:{$sum:"$vms.capacity"}
    }
},
{
  $sort:{_id:1}  
},{
   $project:{
      _id:0,
      "cName":"$_id",
       "capacity":1
   } 
}

])

结果:

{
    "result" : [ 
        {
            "capacity" : 25,
            "cName" : "A"
        }, 
        {
            "capacity" : 117,
            "cName" : "B"
        }
    ],
    "ok" : 1
}

我不明白为什么在你的例子中cName:A capacity = 20 (5+5+5+10)甚至cName:B ......也许它只是模拟