Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB中的数据透视_Mongodb_Mongodb Query - Fatal编程技术网

MongoDB中的数据透视

MongoDB中的数据透视,mongodb,mongodb-query,Mongodb,Mongodb Query,我有一个“文章”集合,一些示例数据可能如下所示: [ {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 Fra

我有一个“文章”集合,一些示例数据可能如下所示:

[
{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查询和独特的聚合,但没有结果

在mongo v2.2中,您可以使用
aggregate
函数:

db.articles.aggregate([
{
//从每个文档中,仅发出标记
$项目:{
标签:1
}
}, {
//为包含的每个标记元素复制每个文档
$unwind:“$tags”
}, {
//按标签的tid和名称对文档进行分组
$group:{
_id:{tid:'$tags.tid',name:'$tags.name'}
}
}, {
//重新调整文档形状以排除_id,并将tid和name置于顶层
$项目:{
_id:0,
tid:“$\u id.tid”,
名称:'$\u id.name'
}
}],
函数(错误、结果){
如果(错误){
console.log('聚合错误:%s',错误);
}否则{
console.dir(结果);
}
});
对于您的文档,这将生成以下输出:

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

最简单的方法是:

db.articles.distinct("tags")
如果您想使用聚合框架(2.2中新增的),则需要更长一些:

db.articles.aggregate([{$unwind:"$tags"}, 
                   {$group:{_id:"$tags"}},
                   {$project:{tid:"$_id.tid",name:"$_id.name",_id:0}}
]).result
提供以下输出:

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

你用什么司机?也许只是在你的业务逻辑中完成,我使用的是mongojs,而且它肯定可以在业务逻辑中完成。我只是想在mongo做尽可能多的工作。