MongoDB——聚合管道之$unwind操作

x33g5p2x  于2022-04-24 转载在 其他  
字(2.5k)|赞(0)|评价(0)|浏览(299)

一、聚合管道之$unwind的概述

  • 可以将数组拆分为单独的文档

二、聚合管道之$unwind的语法格式

  • 注:MongoDB3.2+版本支持如下语法:
{ 
	$unwind: 
		{
		#要指定字段路径,在字段名称前加上$符并用引号括起来。 
		 path: <field path>, 
		#可选,一个新字段的名称用于存放元素的数组索引。该名称不能以$开头。 
		 includeArrayIndex: <string>, 
		#可选,default :false,若为true,如果路径为空,缺少或为空数组,则$unwind输出文档 
		 preserveNullAndEmptyArrays: <boolean> 
	} 
}

三、聚合管道之$unwind的示例

3.1、数据准备

  • 准备数据集,执行脚本
var tags = ["nosql","mongodb","document","developer","popular"];
var types = ["technology","sociality","travel","novel","literature"];
var books=[];
for(var i=0;i<50;i++){
	var typeIdx = Math.floor(Math.random()*types.length);
	var tagIdx = Math.floor(Math.random()*tags.length);
	var tagIdx2 = Math.floor(Math.random()*tags.length);
	var favCount = Math.floor(Math.random()*100);
	var username = "xx00"+Math.floor(Math.random()*10);
	var age = 20 + Math.floor(Math.random()*15);
	var book = {
		title: "book-"+i, 
		type: types[typeIdx],
		tag: [tags[tagIdx],tags[tagIdx2]],
		favCount: favCount, 
		author: {name:username,age:age}
	};
	books.push(book)
}
db.books1.insertMany(books);
  • 查询books1集合中的数据
> db.books1.find()

3.2、将数组拆分为多个文档

  • 统计姓名为xx006的作者的book的tag数组拆分为多个文档
db.books.aggregate([ 
	{$match:{"author.name":"xx006"}}, {$unwind:"$tag"} 
])

  • 解释

  • 查分前后结果对比,如下图:

3.3、统计每个作者的book的tag合集

  • 统计每个作者的book的tag合集
db.books1.aggregate([ 
	{$unwind:"$tag"}, {$group:{_id:"$author.name",types:{$addToSet:"$tag"}}} 
])

  • 解释

3.4、includeArrayIndex选项的示例

  • 新增数据
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"}} 
])

3.5、用preserveNullAndEmptyArrays选项的示例

  • 使用preserveNullAndEmptyArrays选项在输出中包含缺少size字段,null或空数组的文档
db.books1.aggregate([ 
	{$match:{"author.name":"fox"}}, {$unwind:{path:"$tag", preserveNullAndEmptyArrays: true}} 
])

相关文章