2017-01-09 3 views
0

私は、テキストタグの配列を持つフィールドを持つドキュメントセットを持っています。例えば。集計合計配列フィールドからの明瞭な文書Mong​​oDB

{ 
    _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 
} 

(私はいくつかの複雑な$マッチの手順として持っているように、コレクション全体にこれらのタグの個別の出現のカウントを取得したいと思いますよく)、上記の出力を得るために何をすべきかを理解することはできません。このクエリ:

{ 
"_id" : ['foo', 'bar'] 
"count" : 1.0 
}, 
{ 
"_id" : ['foo', 'bar', 'foobar'] 
"count" : 1.0 
} 

多く、事前に感謝:

db.getCollection('collection').aggregate([ 
{$group: {_id: "$tags", count: {$sum: 1}}} 
]) 

は、この結果を生成します。

+2

あなたは '$ unwind'ステップがありません。グループの前に '{$ unwind:" $ tags "}' https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/ – Veeram

+0

そうです。ありがとう。それは常に小さいものです。 TY – matisetorm

答えて

1
db.getCollection('collection').aggregate([ 
{ 
    $unwind : "$tags" 
}, 
{ 
    $group: { 
    _id: "$tags", 
    count: {$sum: 1}} 
} 
]) 
関連する問題