gpt4 book ai didi

MongoDB 对所有文档进行计数和分组

转载 作者:可可西里 更新时间:2023-11-01 09:59:12 28 4
gpt4 key购买 nike

我需要在 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"
}
]}

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

最佳答案

您可以使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com