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

如何将MongoDB集合中的数组字段拆分为多个文档?

MongoDB数组字段拆分为多个文档的方法

原文档

{
  "_id": "12345",
  "Products": [
    "Product1",
    "Product2"
  ],
  "State": "active"
}

期望输出

{
  "_id": "12345",
  "Product": "Product1",
  "State": "active"
}

{
  "_id": "12345",
  "Product": "Product2",
  "State": "active"
}

解决方案

使用MongoDB聚合管道中的$unwind和$project操作符即可实现:

db.collection.aggregate([
  // 将Products数组拆分为单个元素
  { $unwind: "$Products" },
  // 重命名字段并保留所需字段
  {
    $project: {
      _id: 1,
      Product: "$Products",
      State: 1
    }
  }
])

说明

  1. $unwind:将包含数组的文档拆分为多个文档,每个文档对应数组中的一个元素,原数组字段会被替换为单个元素值。
  2. $project:用于重命名Products字段为Product,同时保留_id和State字段,得到符合需求的文档结构。

内容的提问来源于stack exchange,提问作者O'Neil Tomlinson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:34:57