I am working on mongodb to build a simple survey app, the hardest part is to get the statistic using mongodb ‘s aggregation framework.
Here is one submit answers of the survey. The answers property is a array carrying the answers of each question .
{
uid:'xxxx',
surveyId:'xxxxx',
answers:[
{ answer: A }, // question 1 ‘s answer
{ answer: B }, // question 2 ‘s answer
{ answer: C } // question 3 ‘s answer
]
}
The final result I want to have is to know the overall statistic of the survey.
Question 1:
A 50% B 40% C 10%
Question 2:
A 60% B 40% C 0%
The tricky part of mongodb aggregation is how to deal the ‘array’
2
Answers
A simple option is to
$unwind
and$group
:See how it works on the playground example
Or a more generic approach can use
$group
twice without knowing the answer options for each question:See how it works on the playground example
Using custom $accumulator,