首页 文章

在返回的聚合结果中计算变量

提问于
浏览
0

我正在执行聚合,我正在研究如何在原始聚合方法中执行进一步细分 SUM 总量的能力 . 我目前返回距离内的总事件,按群集代码分组 . 我希望按每个类别细分总计数 .

我知道我可以执行 $group 查询

var events = Events.aggregate(
       [
          {
            $match : {
                "location.loc" : {
                   $geoWithin : {
                     $centerSphere : [[long,lat], milesToRadian(radius) ]
                   }
                 }
            }
          },
          {
            $group : {
               _id : { 'cluster_code' : "$location.cluster_code"},
               count : { $sum : 1 }
            }
          }
       ]
    )

我知道我可以在我的 $group 查询中添加一个额外的参数 {"category" : "$category"} 来为每个类别打破这个 . 然后我可以执行分组方法来创建我正在寻找的正确格式 . 这感觉就像我可以改进查询 .

我想要实现的是拥有SUM计数,然后计算每个 category . 与此类似:

{
    "_id": {
      "cluster_code": "FK",
    },
    "Run" : 2,
    "Swim" : 1
    "count": 3
  },

这可能在单个聚合查询中吗?

UPDATE

样本虚拟文件

{
_id : "df",
"location" : {
   //...
},
"category" : "Run"
}

1 回答

  • 0

    您可以在 3.4.4 版本中尝试以下聚合管道 .

    $groupcluster_codecategory 获取每个分组的计数 .

    $zip 每个 category 键值对分别紧跟 $arrayToObject 以创建输出格式结构 .

    使用 $addFieldscluster_codetotal 推入 data .

    使用 $replaceRootdata 嵌入文档提升到最高级别 .

    aggregate(
    {$group : {
           _id : { "cluster_code" : "$location.cluster_code", category:"$category"},
           count : { $sum : 1 }
        }
    },
    {$group : {
          _id : "$_id.cluster_code",
          categorycount : { $push:{category:"$_id.category", count:"$count" }},
          total:{$sum:"$count"}
        }
    },
    {$addFields:{data: {$arrayToObject:{$zip:{inputs:["$categorycount.category", "$categorycount.count"]}}}}},
    {$addFields:{"data.cluster_code": "$_id", "data.total":"$total"}},
    {$replaceRoot:{newRoot:"$data"}}
    )
    

相关问题