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