Home > Blockchain >  Query to count each selected answer of question from array of forms with mongodb
Query to count each selected answer of question from array of forms with mongodb

Time:10-21

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 !

  • Related