0

I'm looking to build a question answer survey system where some questions will be based on the answer of the parent question. The hierarchy level of the questions can go any number of depth based on the questions. The questions and answers will be like the diagram shown here.

enter image description here

I'm looking to build this in mongodb. I have checked the tree model in mongodb and I'm clueless on how to structure it as the next set of questions are depends on the answers. The questions should show based on what answer the user have selected and some answers may have multiple question sets below that as well (E.g.: Ans B).

Can someone help me on the mongodb collection structure and how can I query the next set of questions and answers based on the previous answer given by the user? Thanks in advance.

0

If the whole survey is not too big and if it will not grow, I would consider putting all the questions and answers inside one document.

So one document of that collection would look like

{
  "survey": {
    "Question A": [
      {
        "Ans A": [
          {
            "Question C": [...]
          }
        ]
      },
      {
        "Ans B": [
          {
            "Question D": [...],
            "Question E": [...]
          }
        ]
      }
    ]
  }
}

If it is big, and could grow in future, I would consider putting answer and question ids as key-value pair like following.

{
  "title": "Question A",
  "answers": [
    {
      "Ans A": [
        "Question C's Id"
      ]
    },
    {
      "Ans B": [
        "Question D's Id",
        "Question E's Id"
      ]
    }
  ]
}

I wouldn't normalize to have both question and answer collection, because it would take too much time to join each other.

| improve this answer | |
  • Thanks for the structure. I think the second structure would work well for my scenario. Can you tell me how can I query the next set of questions at once for each direction? – User 99x Jun 4 at 10:21
  • If one chose answer B at question A, then db.questions.find({_id: {$in: ["Question D's Id", "Question E's Id"]}}) will find next set of questions. – Kyoo Sik Lee Jun 5 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.