如何将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 } } ])
说明
$unwind:将包含数组的文档拆分为多个文档,每个文档对应数组中的一个元素,原数组字段会被替换为单个元素值。$project:用于重命名Products字段为Product,同时保留_id和State字段,得到符合需求的文档结构。
内容的提问来源于stack exchange,提问作者O'Neil Tomlinson
相关产品推荐
相关产品推荐

