2012-10-05 46 views
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查询和独特的聚合,但没有结果。

+0

你用什么驱动?也许只是在您的业务逻辑中执行它 – yakxxx

+0

我使用的是mongojs,而且它肯定可以在业务逻辑中完成。我只是尽量在mongo中尽可能多地工作。 – Bagvendt

回答

4

做到这一点,最简单的方法是:

db.articles.distinct("tags") 

如果你想使用聚合框架(2.2中的新功能),它有点lon GER:

db.articles.aggregate([{$unwind:"$tags"}, 
        {$group:{_id:"$tags"}}, 
        {$project:{tid:"$_id.tid",name:"$_id.name",_id:0}} 
]).result 
3

在蒙戈V2.2你可以用aggregate功能做到这一点:

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' } ] 
3
db.articles.distinct("tags") 

给出了下面的输出:

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