【发布时间】: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?只有三个? -
我应该澄清数据是一个截断的例子。忽略总数。这只是一个格式化的例子。为了清楚起见,我将编辑问题。
标签: mongodb mongoose aggregation-framework nosql-aggregation