我有一个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 } } }
]输出根据给定的答案对响应进行计数,但不考虑问题号(元素在数组中的位置)。
我有一个芒果游乐场链接,可能会有帮助:uM7khrMEM
如能提供任何协助,将不胜感激。
发布于 2021-02-11 13:56:48
我不确定有什么最好的方法来做到这一点,但我建议一个聚合查询,
$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" } } }
]https://stackoverflow.com/questions/66144729
复制相似问题