Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.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 - Fatal编程技术网

所有文档中的MongoDB计数和分组依据

所有文档中的MongoDB计数和分组依据,mongodb,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",

我需要在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"
}
]} 
我想我需要使用聚合框架,但我不知道我可以使用什么样的方法。。。
任何人都可以帮助我吗?

您需要从$unwind操作符开始-应该很明显从那里开始。

您可以使用

db..aggregate(
{$project:{'comments.author':1}},
{$unwind:'$comments'},
{$group:{{u id:'$comments.author',cnt:{$sum:1}},
{$sort:{cnt:-1}},
{$limit:1}
);
$project
操作符是可选的

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