0
我有一组文档,其中包含一个带有文本标签数组的字段。例如。Aggregation Sum来自数组字段的不同文档MongoDB
{
_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
}
我试过聚合(我有一些复杂的$匹配步骤好吧),但无法弄清楚如何获得上面的输出。此查询:
db.getCollection('collection').aggregate([
{$group: {_id: "$tags", count: {$sum: 1}}}
])
产生这样的结果:
{
"_id" : ['foo', 'bar']
"count" : 1.0
},
{
"_id" : ['foo', 'bar', 'foobar']
"count" : 1.0
}
预先十分赞赏。
你缺少'$ unwind'步骤。在组之前放置{$ unwind:“$ tags”}。 https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/ – Veeram
是的,就是这样。谢谢。它总是很小。 TY – matisetorm