所有文档中的MongoDB计数和分组依据
我需要在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",
{ _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 }
);