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

MongoDB 3.4:能否用$reduce实现对象数组转嵌套数组?

Using $reduce to Transform Object Arrays into Nested Arrays in MongoDB 3.4

Hey everyone, I've already worked out how to convert object arrays into nested arrays using $unwind and $group in MongoDB 3.4, but I'm curious if there's a way to get the same result with $reduce instead. Let me walk you through the details:

Input Data

{ 
  "myArray": [ 
    {"foo":"x", "bar":"y", "important": { "imp_1": "a", "imp_2": "b" } }, 
    {"foo":"x", "bar":"y", "important": { "imp_1": "aa", "imp_3": "bb" } } 
  ] 
}

Desired Output

{ 
  "myArray": [ 
    {"foo":"x", "bar":"y", "important": [ {"k":"imp_1", "v":"a"}, {"k":"imp_2", "v":"b"} ] },
    {"foo":"x", "bar":"y", "important": [ {"k":"imp_1", "v":"aa"}, {"k":"imp_3", "v":"bb"} ] }
  ] 
}

Solution with $reduce

Absolutely! You can use $reduce for this task—you'll just need to pair it with $objectToArray (to turn the important object into k-v pairs) and $map to loop through your myArray entries. Here's the working aggregation pipeline:

db.collection.aggregate([
  {
    $project: {
      myArray: {
        $map: {
          input: "$myArray",
          as: "item",
          in: {
            foo: "$$item.foo",
            bar: "$$item.bar",
            important: {
              $reduce: {
                input: { $objectToArray: "$$item.important" },
                initialValue: [],
                in: { $concatArrays: ["$$value", ["$$this"]] }
              }
            }
          }
        }
      }
    }
  }
])

If you want a slightly more concise version that still uses $reduce to build the array incrementally, you can swap $concatArrays for $push:

db.collection.aggregate([
  {
    $project: {
      myArray: {
        $map: {
          input: "$myArray",
          as: "item",
          in: {
            foo: "$$item.foo",
            bar: "$$item.bar",
            important: {
              $reduce: {
                input: { $objectToArray: "$$item.important" },
                initialValue: [],
                in: { $push: ["$$value", "$$this"] }
              }
            }
          }
        }
      }
    }
  }
])

Quick Breakdown

  • $map loops through every element in myArray, letting us transform each item one by one.
  • $objectToArray converts the important object into the exact k-v array structure we need for the output.
  • $reduce takes that converted array and builds the final important array by appending each entry to the initial empty array (either via $concatArrays or $push).

Since both $reduce and $objectToArray were introduced in MongoDB 3.4, this pipeline will work perfectly with your version.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:31:16