MongoDB 计算数组中按数组元素分组的匹配字符串

MongoDB Count on matching strings in array grouped by array element

我有一个 MongoDB 集合存储调查的答案。答案通常是带有“优秀”、“好”或“差”等响应的单选按钮。我正在尝试为每个问题生成一个查询 returns 给定响应的总数。响应当前存储在字符串数组中。数组中的位置 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 游乐场 link 可能会有帮助:https://mongoplayground.net/p/4_uM7khrMEM

如有任何帮助,我们将不胜感激。

我不确定是否有最好的方法,但我建议使用一个聚合查询,

  • $unwind解构question数组并在问题
  • 的每个元素的index字段中包含数组索引
  • $arrayElemAt 到 select 提供的 index 字段的特定 answer 以及 type 字段
  • 的相同
  • $group by questionanswer,select 必填字段和总数
  • $group只用question构造answers键值对数组
  • $arrayToObjectanswers 数组转换为对象
[
  {
    $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