如何解决MongoDB 对按数组元素分组的数组中的匹配字符串进行计数
我有一个 MongoDB 集合,用于存储调查的答案。答案通常是带有“优秀”、“良好”或“差”等响应的单选按钮。我正在尝试生成一个查询,该查询为每个问题返回给定响应的总数。响应当前存储在字符串数组中。数组中的位置 0 是问题 1 的答案,依此类推。
[{
"name" : "Medical Visit Survey","question" : [
"Ease of making an appointment?","About how long was your wait time before being seen by the provider?","Professionalism of person who took your call?"
],"type" : [ "radiobutton","radiobutton","radiobutton" ],"answers" : [ "Excellent","Less than 20 minutes","Excellent" ]
},{
"name" : "Medical Visit Survey","answers" : ["Excellent","Very Good" ]
}]
[{
"name" : "Medical Visit Survey","question" : "Ease of making an appointment?","type" : "radiobutton","answers": {
"Excellent": 2,"Good": 3,"Poor": 1
}
},{
"name" : "Medical Visit Survey","question" : "About how long was your wait time before being seen by the provider?","answers": {
"Less than 20 minutes": 2,"More than 20 minutes": 3,"More than 60 minutes": 1
}
}
]
我尝试过类似以下的查询:
[
{$unwind: "$answers" },{ $group: { _id: "$answers",count: { $sum: 1 } } }
]
输出根据给出的答案对响应进行计数,但不考虑问题编号(数组中的元素位置)。
我有一个可能有用的 mongo playground 链接:https://mongoplayground.net/p/4_uM7khrMEM
如有任何帮助,我们将不胜感激。
解决方法
我不确定有没有最好的方法来做到这一点,但我建议使用一个聚合查询,
-
$unwind
解构question
数组并在问题的每个元素的index
字段中包含数组索引 -
$arrayElemAt
选择提供的answer
字段的特定index
,type
字段也相同 -
$group
byquestion
和answer
,选择必填字段并统计总数 -
$group
仅通过question
并以键值格式构造answers
数组 -
$arrayToObject
将answers
数组转换为对象
[
{
$unwind: {
path: "$question",includeArrayIndex: "index"
}
},{
$group: {
_id: {
question: "$question",answer: { $arrayElemAt: ["$answers","$index"] }
},name: { $first: "$name" },type: { $first: { $arrayElemAt: ["$type","$index"] } },count: { $sum: 1 }
}
},{
$group: {
_id: "$_id.question",answers: {
$push: { k: "$_id.answer",v: "$count" }
},type: { $first: "$type" }
}
},{ $addFields: { answers: { $arrayToObject: "$answers" } } }
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。