{
$unwind:
{
#要指定字段路径,在字段名称前加上$符并用引号括起来。
path: <field path>,
#可选,一个新字段的名称用于存放元素的数组索引。该名称不能以$开头。
includeArrayIndex: <string>,
#可选,default :false,若为true,如果路径为空,缺少或为空数组,则$unwind输出文档
preserveNullAndEmptyArrays: <boolean>
}
}
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);
> db.books1.find()
db.books.aggregate([
{$match:{"author.name":"xx006"}}, {$unwind:"$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 }
}
])
db.books.aggregate([
{$match:{"author.name":"fox"}}, {$unwind:{path:"$tag", includeArrayIndex: "arrayIndex"}}
])
db.books1.aggregate([
{$match:{"author.name":"fox"}}, {$unwind:{path:"$tag", preserveNullAndEmptyArrays: true}}
])
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://wwwxz.blog.csdn.net/article/details/124372208
内容来源于网络,如有侵权,请联系作者删除!