转载:猿天地 链接:http://cxytiandi.com/blog/detail/2940
$unwind的作用是将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
官方文档地址:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/
比如文章信息有标签tags,值有java,mongodb,spring
{
"_id": 1001,
"tags": [
"java",
"mongodb",
"spring"
]
}
假如我们要将tags拆分显示,也就是每个tag都显示成一条单独的数据
db.article_info.aggregate( { $unwind : "$tags" })
结果如下:
{ "_id" : 1001, "tags" : "java" }
{ "_id" : 1001, "tags" : "mongodb" }
{ "_id" : 1001, "tags" : "spring" }
假如我们的需求是统计每个tag出现的次数
这个时候就需要用到先将$unwind tags拆分,然后根据具体的tag来做分组统计
> db.article_info.aggregate(
... { $unwind : "$tags" },
... { $group : { "_id" : "$tags", "count" : { $sum : 1 } } },
... { $project : { "tag" : "$_id", "count" : 1 } }
... )
结果如下:
{ "_id" : "spring", "count" : 1, "tag" : "spring" }
{ "_id" : "mongodb", "count" : 1, "tag" : "mongodb" }
{ "_id" : "java", "count" : 1, "tag" : "java" }