MongoDB query/aggregation needed: If I have an array, how can I group documents depending on different values in an array? Example:
If I have these objects:
> db.respondents.insert({person: 1, responses: [{question: 'How old are you?', response: '18-40 yrs'}, {question: 'What is the brand of your car?', response: 'Fiat'} ] } )
> db.respondents.insert({person: 2, responses: [{question: 'How old are you?', response: '18-40 yrs'}, {question: 'What is the brand of your car?', response: 'Volvo'} ] } )
> db.respondents.insert({person: 3, responses: [{question: 'How old are you?', response: '41-65 yrs'}, {question: 'What is the brand of your car?', response: 'Volvo'} ] } )
> db.respondents.insert({person: 4, responses: [{question: 'How old are you?', response: '41-65 yrs'}, {question: 'What is the brand of your car?', response: 'Volvo'} ] } )
And would like to write a query which tells me what car brand respondents own (aka base question) per age group (aka breakdown question)?
So the answer should tell me:
1 person in age group '18-40' responded 'Fiat' to question 'What is the brand of you car?'
1 person in age group '18-40' responded 'Volvo' to question 'What is the brand of you car?'
2 persons in age group '41-65' responded 'Volvo' to question 'What is the brand of you car?'
And IRL:
- There are 100.000+ respondents
- There are about 30 'responses' per respondent
- MongoDb 3.0.9 is used
I've tried numerous ways but won't bore you with my failures....