目录
一、聚合管道之$unwind的概述
- 一、聚合管道之$unwind的概述
- 二、聚合管道之$unwind的语法格式
- 三、聚合管道之$unwind的示例
- 3.1、数据准备
- 3.2、将数组拆分为多个文档
- 3.3、统计每个作者的book的tag合集
- 3.4、includeArrayIndex选项的示例
- 3.5、用preserveNullAndEmptyArrays选项的示例
- 可以将数组拆分为单独的文档
-
注: MongoDB3.2+版本支持如下语法:
{ $unwind: { #要指定字段路径,在字段名称前加上$符并用引号括起来。 path: , #可选,一个新字段的名称用于存放元素的数组索引。该名称不能以$开头。 includeArrayIndex: , #可选,default :false,若为true,如果路径为空,缺少或为空数组,则$unwind输出文档 preserveNullAndEmptyArrays: } }
-
准备数据集,执行脚本
var tags = ["nosql","mongodb","document","developer","popular"]; var types = ["technology","sociality","travel","novel","literature"]; var books=[]; for(var i=0;i db.books1.find()
-
统计姓名为xx006的作者的book的tag数组拆分为多个文档
db.books.aggregate([ {$match:{"author.name":"xx006"}}, {$unwind:"$tag"} ])
-
解释
-
查分前后结果对比,如下图:
-
统计每个作者的book的tag合集
db.books1.aggregate([ {$unwind:"$tag"}, {$group:{_id:"$author.name",types:{$addToSet:"$tag"}}} ])
-
解释
-
新增数据
db.books1.insert([ { "title" : "book-51", "type" : "technology", "favCount" : 11, "tag":[], "author" : { "name" : "fox", "age" : 28 } }, { "title" : "book-52", "type" : "technology", "favCount" : 15, "author" : { "name" : "fox", "age" : 28 } }, { "title" : "book-53", "type" : "technology", "tag" : [ "nosql", "document" ], "favCount" : 20, "author" : { "name" : "fox", "age" : 28 } } ])
-
使用includeArrayIndex选项来输出数组元素的数组索引
db.books.aggregate([ {$match:{"author.name":"fox"}}, {$unwind:{path:"$tag", includeArrayIndex: "arrayIndex"}} ])
-
使用preserveNullAndEmptyArrays选项在输出中包含缺少size字段,null或空数组的文档
db.books1.aggregate([ {$match:{"author.name":"fox"}}, {$unwind:{path:"$tag", preserveNullAndEmptyArrays: true}} ])