我需要在 mongodb 数据库中进行查询:
我需要获取所有文档中重复次数最多的作者字段,但该字段位于数组文档中..
{ _id:'1234567',
date:'9/27/08 3:21',
a_name:'name',
a_nick:'nick',
comments: [
{
body:"aa",
email:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b2a0b2a65282426" rel="noreferrer noopener nofollow">[email protected]</a>,
author: "Author a"
},
{
body:"bb",
email:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f496b496da979b99" rel="noreferrer noopener nofollow">[email protected]</a>,
author: "Author b"
},{
body:"cc",
email:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8ead8ec38e8280" rel="noreferrer noopener nofollow">[email protected]</a>,
author: "Author c"
}
]}
我认为我需要使用聚合框架,但我不知道我可以使用女巫条款...... 有谁可以帮助我吗?
最佳答案
您可以使用 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
运算符是可选的。
关于MongoDB 对所有文档进行计数和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23228419/