需要记住的是,MongoDB采用“NoSQL”方法来存储数据,因此从你的头脑中删除选择、连接等操作的想法。它存储数据的方式是以文档和集合的形式,这允许动态地向存储位置添加和获取数据。
话虽如此,为了理解“$unwind”参数背后的概念,首先必须理解你尝试引用的用例在表达什么。来自mongodb.org的示例文档如下:
{
title : "this is my title" ,
author : "bob" ,
posted : new Date () ,
pageViews : 5 ,
tags : [ "fun" , "good" , "fun" ] ,
comments : [
{ author :"joe" , text : "this is cool" } ,
{ author :"sam" , text : "this is bad" }
],
other : { foo : 5 }
}
请注意,tags实际上是一个由3个项组成的数组,本例中为“fun”,“good”和“fun”。
$unwind的作用是允许您为每个元素剥离一个文档,并返回该结果文档。
从经典方法来看,这相当于“对于tags数组中的每个项目,返回仅包含该项的文档”。
因此,运行以下内容的结果如下:
db.article.aggregate(
{ $project : {
author : 1 ,
title : 1 ,
tags : 1
}},
{ $unwind : "$tags" }
);
将返回以下文件:
{
"result" : [
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "fun"
},
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "good"
},
{
"_id" : ObjectId("4e6e4ef557b77501a49233f6"),
"title" : "this is my title",
"author" : "bob",
"tags" : "fun"
}
],
"OK" : 1
}
请注意,结果数组中唯一变化的是将返回值 tags 值更改了。如果您需要有关此操作方式的其他参考资料,请查看此链接:here。
$summary.tags
... 我想去重并统计 $size。 - chovy