You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB聚合查询的data数组转为根层级结果?

MongoDB聚合查询:将数组内容转为根层级结果

现有聚合查询

db.demo.aggregate([
{
    '$group':
        {   '_id': null, 
            "Bytes Sent":{"$sum": "$sentBytes"},
            "Bytes Received":{"$sum":"$recivedBytes"}
        }
},
{
    "$project":{
        "data":[
                {"Count":"$Bytes Sent","Name":"Bytes Sent"},
                {"Count":"$Bytes Received","Name":"Bytes Received"}
               ] 
           }
       }
  ])

当前输出结果

{
"_id" : null,
"data" : [
    {
        "Count" : NumberLong("22893994106"),
        "Name" : "Bytes Sent"
    },
    {
        "Count" : NumberLong("16574618640"),
        "Name" : "Bytes Received"
    }
]}

需求

将data数组中的内容直接作为根层级结果输出,格式如下:

{
    "Count" : NumberLong("22893994106"),
    "Name" : "Bytes Sent"
},
{
    "Count" : NumberLong("16574618640"),
    "Name" : "Bytes Received"
}

解决方案

在原聚合管道末尾添加两个阶段:$unwind和$replaceRoot(或$replaceWith),修改后的完整聚合语句如下:

db.demo.aggregate([
  {
    '$group': {
      '_id': null, 
      "Bytes Sent": {"$sum": "$sentBytes"},
      "Bytes Received": {"$sum": "$recivedBytes"}
    }
  },
  {
    "$project": {
      "data": [
        {"Count": "$Bytes Sent", "Name": "Bytes Sent"},
        {"Count": "$Bytes Received", "Name": "Bytes Received"}
      ]
    }
  },
  // 展开data数组,将数组每个元素转为独立文档
  { "$unwind": "$data" },
  // 将data字段的内容替换为根文档,去掉外层包装
  { "$replaceRoot": { "newRoot": "$data" } }
])

步骤说明

  1. $unwind阶段:把包含data数组的单个文档拆分成多个文档,每个文档对应数组中的一个元素,此时每个文档结构为{ "_id": null, "data": {...} }
  2. $replaceRoot阶段:将每个文档的data字段内容提升为根层级,最终输出就是数组中的每个独立对象

注:MongoDB 4.2及以上版本可以用$replaceWith替代$replaceRoot,写法更简洁:{ "$replaceWith": "$data" },效果完全一致。

内容的提问来源于stack exchange,提问作者Avinash Utekar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:48:16