I'm getting a little issue with a Mongo DB query.
I have a collection called "Answers" with the following structure
{
"_id": ObjectId("560acfcb904a29446a6d2617"),
"path_id": ObjectId("560acae1904a29446a6d2610"),
"step_id": "kids",
"user_id": ObjectId("559ae27684ff12e88d194eb7"),
"answers": [
{
"id": "kids_q",
"question": "Do you have kids?",
"answer": "No"
}
]
}
As you can see answers is an array and it can have one or many objects, but always is an array.
First, I want to get the total of answers in a step_id
I get that using the following query using aggregate
Answer.aggregate( {
$match: {
'path_id': {
$eq: path_id
},
'step_id': {
$eq: step_id
},
''
}
}, {
$group: {
_id: {
step_id: '$step_id'
},
count: {
$sum: 1
}
}
}, function( err, results ) {
if ( err ) {
deferred.reject( err );
}
deferred.resolve( results );
} );
That works great.
Second, I want to get how many of that answers match against the question and the answer.
Let's use the Do you have kids? question as example, I want to know how many answers are Yes, running a query in the command line I get the correct result:
db.answers.find( {
path_id: ObjectId( '560acae1904a29446a6d2610' ),
'answers.0.question': 'Do you have kids?',
'answers.0.answer': 'Yes'
} )
I want to translate that query into an aggregate query using mongoose and avoid to have hard coded the array answers.0.question because that answer can be stored in a random index, maybe in the index 1, maybe in the index 7.
Any help is appreciated.
Thanks