[英]`$group` by unique items in array
假设我们有类似的文件
[
{tags: ['a', 'b', 'c']},
{tags: ['b', 'c', 'd']}
]
那么,我们如何计算每个标签的文档数呢?
[
{_id: 'a', count: 1},
{_id: 'b', count: 2},
{_id: 'c', count: 2},
{_id: 'd', count: 1}
]
因为在$tags
上进行正常的$group
会(当然)会产生不同的结果。
我认为以下查询将为您提供结果。 $unwind
是关键。
db.collection_name.aggregate( [ { $unwind : "$tags" },
{ $group : { _id : "$tags", total : { $sum : 1 } } }] )
供参考-https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.