说明
对数据进行展开聚合查询,更多的是针对数组
完整语法
{
$unwind:
{
path: <field path>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
}
}
通过例子可以更好的理解
例一:
创建一个inventory的collection 并插入一条数据
db.inventory.insertOne({ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] })
下面这句话,使用$unwind,将sizes查分成单独的数据
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )
输出结果
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }
例二:
处理不存在的情况
db.clothing.insertMany([
{ "_id" : 1, "item" : "Shirt", "sizes": [ "S", "M", "L"] },
{ "_id" : 2, "item" : "Shorts", "sizes" : [ ] },
{ "_id" : 3, "item" : "Hat", "sizes": "M" },
{ "_id" : 4, "item" : "Gloves" },
{ "_id" : 5, "item" : "Scarf", "sizes" : null }
])
再次用$unwind进行聚合查询
db.clothing.aggregate( [ { $unwind : "$sizes" } ] )
返回结果:
{ _id: 1, item: 'Shirt', sizes: 'S' },
{ _id: 1, item: 'Shirt', sizes: 'M' },
{ _id: 1, item: 'Shirt', sizes: 'L' },
{ _id: 3, item: 'Hat', sizes: 'M' }
id为1和3能返回,2、4、5则没有返回,因为他们sizes没有数据
如果想返回,则通过preserveNullAndEmptyArrays,设置成tree
db.clothing.aggregate( [
{ $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }
] )
如果想返回对应的下标,则通过includeArrayIndex
{ _id: 1, item: 'Shirt', sizes: 'S', arrayIndex: 0 },
{ _id: 1, item: 'Shirt', sizes: 'M' , arrayIndex: 1},
{ _id: 1, item: 'Shirt', sizes: 'L' , arrayIndex: 2},
{ _id: 3, item: 'Hat', sizes: 'M' , arrayIndex: null} // 因为他不是一个数组,返回一个null
MongoDB$unwind操作详解:展开聚合查询
文章介绍了MongoDB中的$unwind操作符,用于在聚合查询中展开数组字段。通过示例展示了如何使用$unwind将数组元素拆分为单独的文档,以及如何处理空数组和null值,包括使用`preserveNullAndEmptyArrays`参数以及`includeArrayIndex`来包含索引信息。
1046

被折叠的 条评论
为什么被折叠?



