【问题标题】:Aggregate a result set with node.js and mongodb in nested Array Structure在嵌套数组结构中使用 node.js 和 mongodb 聚合结果集
【发布时间】:2018-08-02 03:38:32
【问题描述】:

在这里阅读了多年并找到了很好的答案,这是我在 stackoverflow 上的第一篇文章,因为我正面临 node.js 和 mongodb 的问题。

我正在开发一个轮询系统,具有以下数据结构。

mongodb数据结构

{
    "_id" : "abcde",
    "course" : "FIAE17K",
    "poll" : "Poll1",
    "answers" : [ 
        {
            "question" : "Question1",
            "answer" : 1
        }, 
        {
            "question" : "Question2",
            "answer" : 2
        }, 
        {
            "question" : "Question3",
            "answer" : 1
        }
    ]
}

{
    "_id" : "abcd",
    "course" : "FIAE17J",
    "poll" : "Poll1",
    "answers" : [ 
        {
            "question" : "Question1",
            "answer" : 3
        }, 
        {
            "question" : "Question2",
            "answer" : 2
        }
    ]
}

我想对投票进行评估,并且可能想生成这样的 JSON 结构...可能我需要在服务器端进行一些转换才能获得这种格式!结果数组需要收集特定问题的答案数量,例如。问题 1 回答 1 次,回答 3 次。

“完美”结果集

[
    {
        "titel": "Question1",
        "results": [1,0,1]
    },
    {
        "titel": "Question2",
        "results": [0,2]
    },
    {
        "titel": "Question3",
        "results": [1]
    }
]

据我了解,我需要使用 mongodb 执行 聚合函数,包括 $group 语句。但是不知道怎么弄,我是这样开始的……

db.antworten.aggregate([
    {$match: {"course":/FI/}},
    ?????
])

【问题讨论】:

  • 为什么问题 1 的结果是 [1,0,1] 而不是 [1,3]?
  • 因为 Question1 回答了 1 次,回答了 1 次,回答了一次回答了 3。所以输出是 [1,0,1],但任何其他有助于我评估投票的输出都是可能的。

标签: node.js mongodb-query grouping aggregate-functions


【解决方案1】:

通过这个聚合函数,我已经更接近于我正在寻找的东西了:

db.anwers.aggregate([
    {$match: {"course":/FI/,"poll":"Poll1"}},
    {$unwind: "$answers"},
    {$group: {_id: "$answers",count:{$sum:1}}},
    {$sort: {_id: 1}}   
])

这个生产

{
    "_id" : {
        "question" : "Question1",
        "answer" : 1
    },
    "count" : 1.0
}

{
    "_id" : {
        "question" : "Question1",
        "answer" : 3
    },
    "count" : 1.0
}

{
    "_id" : {
        "question" : "Question2",
        "answer" : 2
    },
    "count" : 2.0
}

{
    "_id" : {
        "question" : "Question3",
        "answer" : 1
    },
    "count" : 1.0
}

可能是我可以在服务器端做的其余部分,或者是否有人找到其他选项,这样我就不必将所有多余的问题返回给客户端?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2017-07-26
    • 2020-01-24
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多