在嵌套的Array Structure中使用node.js和mongodb聚合结果集

问题描述 投票:0回答:1

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

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

mongodb Data Structure

{
    "_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回答一次。

The 'perfect' Result Set

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

据我所知,我需要使用mongodb进行聚合函数,包括$ group语句。但我不知道如何,我开始如下......

db.antworten.aggregate([
    {$match: {"course":/FI/}},
    ?????
])
node.js mongodb-query grouping aggregate-functions
1个回答
0
投票

我已经更接近我正在寻找的这个聚合函数:

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
}

可能是我在服务器端可以做的其余部分,或者是否有人找到另一个选项,以便我不必将所有冗余的问题都返回给客户端?

© www.soinside.com 2019 - 2024. All rights reserved.