Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
Mongoose how to implement nested queries

My db schema is

Collection - Question

 {
        "_id" : ObjectId("588f79d7535415ceb7a026bd"),
        "type" : 1,
        "question" : "Who is the best bastman from the following:",
        "options" : [ 
            "Sachin Tendulkar", 
            "Rahul Dravid"
        ]
    }

Collection - Answers

{
    "questionId" : "588f79d7535415ceb7a026bd",
    "answers" : [ 
        {
            "userId" : [ 
                102, 
                101, 
                105
            ]
        }
    ]
}

I created an API to get all the Questions and for each "_Id" i need to access the collection- Answers and retrieve the answer corresponding to that questionId. How can i achieve this? .

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I would recommend you to embed the answer in the question collection.

{
    "_id" : ObjectId("588f79d7535415ceb7a026bd"),
    "type" : 1, 
    "question" : "Who is the best bastman from the following:",
    "options" : [ 
        "Sachin Tendulkar", 
        "Rahul Dravid"
    ],
    "answers": [{
         "userId":[102,101,105]             
     }]
}

Schema:-

{
    "type" : Number, 
    "question" : String,
    "options" : [String],
    "answers": [{
         "userId":[Number]             
     }]
}

Or:-

if only userIds will be added in future to the answers, then you can make answers an Object instead of an array of objects, that depends on your application logic.

{
    "type" : Number, 
    "question" : String,
    "options" : [String],
    "answers": {
         "userId":[Number]             
     }
}

Now you do not need to run two queries for retrieving both questions and answers for a particular question. If you need to retrieve data in custom format, you have to use MongoDB Aggregation framework

If you want to know more about the embedded data model design in MongoDB, please refer to this documentation

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!