2

「記事」コレクションがあり、サンプル データは次のようになります。

[
{body: 'Interesting news in Siberia and so on etc. etc. etc. and lolcats too',
author: 'John Doe',
tags: [{tid:24, name: "Siberia"}, 
       {tid: 5231, name: "Lolcats"},]
},
{body: 'Something is going on in Siberia and France',
author: 'Jane Doe',
tags: [{tid:24, name: "Siberia"}, 
       {tid: 6432, name: "France"},]
},
]

そして、私の必要な出力は、タグの個別のリストです。

[
{tid: 24, name: 'Siberia'},
{tid: 5231, name: 'Lolcats'},
{tid: 6432, name: 'France'},
]

いくつかの mapReduce クエリと個別の集計に苦労していますが、結果はありません。

4

3 に答える 3

4

これを行う最も簡単な方法は次のとおりです。

db.articles.distinct("tags")

集約フレームワーク (2.2 の新機能) を使用する場合は、少し長くなります。

db.articles.aggregate([{$unwind:"$tags"}, 
                   {$group:{_id:"$tags"}},
                   {$project:{tid:"$_id.tid",name:"$_id.name",_id:0}}
]).result
于 2012-10-05T13:00:41.133 に答える
3
db.articles.distinct("tags")

次の出力が得られます。

[
{
    "tid" : 24,
    "name" : "Siberia"
},
{
    "tid" : 5231,
    "name" : "Lolcats"
},
{
    "tid" : 6432,
    "name" : "France"
}
]
于 2012-10-05T13:07:57.403 に答える
3

aggregatemongo v2.2 では、次の関数を使用してこれを行うことができます。

db.articles.aggregate([
{
    // From each document, emit just the tags
    $project: {
        tags: 1
    }
}, {
    // Duplicate each document for each tags element it contains
    $unwind: '$tags'
}, {
    // Group the documents by the tag's tid and name
    $group: {
        _id: { tid: '$tags.tid', name: '$tags.name' }
    }
}, {
    // Reshape the document to exclude the _id and bring tid and name to the top level
    $project: {
        _id: 0,
        tid: '$_id.tid',
        name: '$_id.name'
    }
}],
function (err, result) {
    if (err) {
        console.log('aggregation error: %s', err);
    } else {
        console.dir(result);
    }
});

ドキュメントの場合、これにより次の出力が生成されます。

[ { tid: 6432, name: 'France' },
  { tid: 5231, name: 'Lolcats' },
  { tid: 24, name: 'Siberia' } ]
于 2012-10-05T12:34:31.583 に答える