MongoDB从所有文档计数和分组

时间:2014-04-22 19:22:56

标签: mongodb

我需要在mongodb数据库中进行查询:

我需要在所有文档中获取最重复的作者字段,但是这个字段里面有一个数组文档..

{ _id:'1234567', 
date:'9/27/08 3:21', 
a_name:'name', 
a_nick:'nick', 
comments: [
{
body:"aa",
email:a@a.com,
author: "Author a"
},
{
body:"bb",
email:b@b.com,
author: "Author b"
},{
body:"cc",
email:c@c.com,
author: "Author c"
}
]} 

我想我需要使用聚合框架,但我不知道我可以使用的巫婆条款...... 任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:5)

您可以使用aggregation framework

$unwind$group运算符
db.<collection>.aggregate( 
   { $project: { 'comments.author':1 } }, 
   { $unwind: '$comments' }, 
   { $group: {_id: '$comments.author', cnt: { $sum:1 } } }, 
   { $sort: { cnt:-1 } }, 
   { $limit:1 } 
);

$project运算符是可选的。

答案 1 :(得分:0)

你想要从$ unwind运算符开始 - http://docs.mongodb.org/manual/reference/operator/aggregation/unwind/应该相当明显从哪里开始。

相关问题