微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MongoDB 对按数组元素分组的数组中的匹配字符串进行计数

如何解决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 字段的特定 indextype 字段也相同
  • $group by questionanswer,选择必填字段并统计总数
  • $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" }
      },type: { $first: "$type" }
    }
  },{ $addFields: { answers: { $arrayToObject: "$answers" } } }
]

Playground

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。