如何使用mongodb的聚合

时间:2014-01-03 18:40:42

标签: mongodb aggregation-framework

根据下面给出的数据,我想对所有值字段求和。 请让我知道如何使用mongodb的聚合功能来实现它。

{"MetricRecord": 
   { "SchemaVersion" :  "0.12",
     "Product": {
         "ProductName"   : "abc",
         "ProductVersion": "7.5.0.1" ,
         "ProductId"     : "1234567890ABDFGH12345",
         "InstanceId"    : "12345BA32",
         "InstanceName"  : "1234SS123",
         "SystemId"      : "somehost.com" 
         },
     "Tenant" : {
       "CustomerId" : "222-555-124", 
       "ServiceCode": "xyzxyzxyz12345yyy"
         },
     "Metrics" :  [
      {   
       "ReportType" :[ 
          { "report" : "billing" },           
        ],
          "LogTime" : "2013-12-08T12:34:56:01Z" ,
          "Type"    : "AuthorizedUsers",
          "SubType" : "registered",
          "Value"   : "125",
          "UnitOfMeasure": "USD",
        "Period"  :  {
            "StartTime" : "2013-12-07T00:00:00:01Z",
            "EndTime"   : "2013-12-08T00:00:00:01Z"
          }
          },
      {   
       "ReportType" :[ 
          { "report" : "billing" }
        ],
          "LogTime" : "2013-12-08T12:34:56:01Z" ,
          "Type"    : "NumberOfTickets",
          "SubType" : "resolved",
          "Value"   : "430",
          "UnitOfMeasure": "USD",
        "Period"  :  {
            "StartTime" : "2013-12-07T00:00:00:01Z",
            "EndTime"   : "2013-12-08T00:00:00:01Z"
          }
          }
       ]
    }
 }

因此,我期望从值的总和得到的结果是430 + 125,即555

1 个答案:

答案 0 :(得分:0)

您的文档包含MetricRecord.Metrics [index] .Value 字段的字符串值,我不确定您为什么要总结字符串值。如果是拼写错误并且您的文档包含 MetricRecord.Metrics [index] .Value 字段的数值,那么您可以尝试以下查询

db.metrics.aggregate([
                      {$unwind:"$MetricRecord.Metrics"},
                      {$group:{_id:"$_id",sum:{$sum:"$MetricRecord.Metrics.Value"}}}
                    ])

在上面发布的文档中,如果您的值字段是

 MetricRecord.Metrics[0].Value is 125(not "125")
 MetricRecord.Metrics[1].Value is 430(not "430")

您将获得以下输出

{
"result" : [
    {
        "_id" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
        "sum" : 555
    }
],
"ok" : 1
}

假设您拥有默认的mongodb " _id" 字段并且您使用指标集合,则会构成上述示例查询。您必须根据您的要求操纵查询。