MongoDB计数按数组元素分组的数组中的匹配字符串
Posted
技术标签:
【中文标题】MongoDB计数按数组元素分组的数组中的匹配字符串【英文标题】:MongoDB Count on matching strings in array grouped by array element 【发布时间】:2021-05-14 14:28:46 【问题描述】:我有一个存储调查答案的 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",
"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", "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?",
"type" : "radiobutton",
"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 游乐场链接:https://mongoplayground.net/p/4_uM7khrMEM
任何帮助将不胜感激。
【问题讨论】:
你的例子没有加起来,你怎么能得到"Excellent": 4
?只有三个?
我应该澄清数据是一个截断的例子。忽略总数。这只是一个格式化的例子。为了清楚起见,我将编辑问题。
【参考方案1】:
我不确定有没有最好的方法,但我会建议一个聚合查询,
$unwind
解构 question
数组并在每个问题元素的 index
字段中包含数组索引
$arrayElemAt
选择提供的index
字段中的特定answer
,对于type
字段也相同
$group
by question
和 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"
,
name: $first: "$name" ,
type: $first: "$type"
,
$addFields: answers: $arrayToObject: "$answers"
]
Playground
【讨论】:
以上是关于MongoDB计数按数组元素分组的数组中的匹配字符串的主要内容,如果未能解决你的问题,请参考以下文章