I’m new to using MongoDB queries.
I would like to count the number of selected answers based on the question.
Here is an example of data I’m trying to process:
{
"_id": "910ef391-bc06-4fda-80c5-c6a6d9bcXXXX",
"book": {
"register": [
{
"questions": [
{
"id": "87b8c60c-9c9e-41d1-a52a-588400deXXXX",
"name": "Question A",
"answers": [
{
"_id": 1,
"label": "Answer 1",
"selected": true
},
{
"_id": 2,
"label": "Answer 2",
"selected": false
}
]
},
{
"id": "55b8c60c-9c9e-41d1-a52a-588400deXXXX",
"name": "Question B",
"answers": [
{
"_id": 1,
"label": "Answer 1",
"selected": true
},
{
"_id": 2,
"label": "Answer 2",
"selected": false
}
]
}
]
}
]
}
},
{
"_id": "120ef391-bc06-4fda-80c5-c6a6d9bcXXXX",
"book": {
"register": [
{
"questions": [
{
"id": "99b8c60c-9c9e-41d1-a52a-588400deXXXX",
"name": "Question A",
"answers": [
{
"_id": 1,
"label": "Answer 1",
"selected": true
},
{
"_id": 2,
"label": "Answer 2",
"selected": false
}
]
}
]
}
]
}
}
]
Here is the expected result:
[
{
"Answer 1": 2
}
]
I would like to count the number of selected answers to question A.
I’ve tried something, but it returns no document found
db.collection.aggregate([
{
$group: {
_id: "$book.register.questions",
questions: {
$push: "$book.register.questions"
}
}
},
{
$match: {
"questions.name": "Question A"
}
}
])
Thank you for your help !🤙
2
Answers
It works !!! Just move the first
$match
pipeline after the$unwind
pipeline:"$book.register.questions"
. @Yong Shun => Thank you very much for your answer, your reactivity and your quality of response !A bit long query.
$match
– Filter the document with dot notation to find the document containing "Question A".$unwind
– Deconstructbook.register
array into multiple documents.$unwind
– Deconstructbook.register.questions
array into multiple documents.$unwind
– Deconstructbook.register.questions.answers
array into multiple documents.$group
– Group bybook.register.questions.answers.label
and perform conditional total sum based onbook.register.questions.answers.selected
value. Add 1 if it is true.$group
– Group bynull
. This aims to combine all the documents into a single document by pushing the answer label and count into theanswers
array.$replaceWith
– Replace the input document to convert from theanswers
array into key-value pair.Demo @ Mongo Playground