我有一组文档,其中包含一个带有文本标记数组的字段。例如。
{
_id: uXFLH__St8o3NfxwMa53ig,
tags: ['foo', 'bar', 'foobar']
},
{
_id: DWbe__3fegKXBa_Ai3CGRQ,
tags: ['foo', 'bar']
}
我想计算整个集合中这些标记的不同出现次数,以便输出
{
"_id": "foo",
count: 2
},
{
"_id": "bar",
count: 2
},
{
"_id": "foobar",
count: 1
}
我已经尝试过聚合(我也有一些复杂的$ match步骤),但无法弄清楚要做什么来获得上面的输出。这个查询:
db.getCollection('collection').aggregate([
{$group: {_id: "$tags", count: {$sum: 1}}}
])
产生这个结果:
{
"_id" : ['foo', 'bar']
"count" : 1.0
},
{
"_id" : ['foo', 'bar', 'foobar']
"count" : 1.0
}
事先得到很多赞赏。
答案 0 :(得分:1)
db.getCollection('collection').aggregate([
{
$unwind : "$tags"
},
{
$group: {
_id: "$tags",
count: {$sum: 1}}
}
])