mongodb - 如何对集合进行分组以汇总对象的属性并使用 MongoDB 生成计算字段
问题描述
如何按特定字段对集合进行分组并生成一个使用 mongoDB 对象的属性总和计算的字段,我不知道是否可以做我想做的事情,但我想知道。
我想按duelId字段分组以添加分数集合:
{ "matches": [{
"secondParticipant": {"name": "Maria","battlesWon": 2},
"firstParticipant": {"name": "Fabio","battlesWon": 1},
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102",
},{
"secondParticipant": {"name": "Fabio","battlesWon": 1 },
"firstParticipant": {"name": "Maria","battlesWon": 1 },
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102"
},
{
"secondParticipant": {"name": "Luiz","battlesWon": 1},
"firstParticipant": {"name": "Jose","battlesWon": 1},
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a666"
}]}
预期的:
{[ [
{
"secondParticipant": {"name": "Maria","battlesWon": 2 },
"firstParticipant": {"name": "Fabio","battlesWon": 1 },
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102",
},{
"secondParticipant": {"name": "Fabio","battlesWon": 1},
"firstParticipant": {"name": "Maria","battlesWon": 1},
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a102"
},
"score": { "Fabio": 2, "Maria": 3 } *// this field would be the sum of battlesWon after grouping*
],
[
{
"secondParticipant": {"name": "Luiz","battlesWon": 1},
"firstParticipant": {"name": "Jose","battlesWon": 1},
"duelId": "6c3e532d-3c0e-4438-8289-c86a4a51a666"
},
"score": { "Luiz": 1, "Jose": 1 } // *this field would be the sum of battlesWon after grouping*
]]}
解决方案
您可以执行以下操作:
$unwind
matches
数组_- 重命名
firstParticipant
并secondParticipant
放入 kv 元组数组以进行进一步处理 - 按决斗和名称分组,总结每个参与者的分数
- 按决斗分组以获取每个决斗请求的名称分数元组
- 用于
$arrayToObject
将步骤 2 中的 kv 元组数组转换回请求的形式。
这是Mongo Playground供您参考。
推荐阅读
- hyperlink - 如何在 BigQuery 中存储超链接数据,然后获得激活的链接 Google DataStudio。?
- r - 如何将整洁的数据集转换为适合冲积层的格式?(冲积层)
- azure - 用于 Azure Blob 存储的 SAS 令牌 - 是否可以为要上传的文件创建令牌?只写?
- jira - Jira:如果 webhook 返回错误响应,如何恢复操作?
- firebase - FirebaseAuth REST API getOobConfirmationCode 不起作用
- javascript - Chrome 扩展程序上的桌面通知不起作用
- r - 用`-`符号重命名R中的列
- django - Django rest - 如何序列化预取相关集?
- java - Sonarqube 7.6 无法使用 Gradle 插件加载组件类 org.sonar.plugins.checkstyle.CheckstyleExecutor
- mysql - 无法安装 MySQL 连接器库