Search code examples
node.jsmongodbmongodb-querymongoose-schema

Unable to perform complex nesting in mongodb queries?


how to perform complete nesting in mongodbquery


Solution

  • There are many ways you can do this, here is an example by nesting $lookup's :

    [
        {
            '$lookup': {
                'from': 'questionsanwereds',
                'let': {id: '$_id'},
                "pipeline": [
                    {
                        $match: {
                            $expr: {
                                $eq: ["$$id", "$reqId"]
                            }
                        }
                    },
                    {
                        $unwind: "$questions"
                    },
                    {
                        $lookup: {
                            from: "questions",
                            localField: "questions.questionId",
                            foreignField: "_id",
                            as: "questionObj"
                        }
                    },
                    {
                        "$unwind": "$questionObj"
                    },
                    {
                        $group: {
                            _id: "$_id",
                            questions: {
                                $push: {
                                    comment: "$comment",
                                    name: "$questionObj.name",
                                    optionSelected: "$optionSelected"
                                }
                            }
                        }
                    }
                ],
                'as': 'questionsAnswereds'
            }
        },
        {
            '$unwind': {
                'path': '$questionsAnswereds'
            }
        }
    ]
    

    The strategy is populating the name of each question separately and then grouping to restore the required structure.