Nested inside nested Objects with same key aggregation with another collection in mongoDB

Viewed 69

Here I am placing example collections and expected output. I have nested modules array of objects

When I get request from the api as student Id, course id & module id then I have to send module % if exists if not need to send % as 0

Course collection

{
    "_id": "courseId1",
    "courseName": "course1",
    "isActive": true,
    "modules": [
                    {
                    "_id":"id1",
                    "name":"mod1",
                    "isActive": true
                    },
                    {
                    "_id":"id2",
                    "name":"mod2",
                    "isActive": true
                    
                    },
                    {
                    "_id":"id3",
                    "name":"mod3",
                    "isActive": true
                      "modules":[
                          {
                          "_id":"id4",
                          "name":"mod4",
                          "isActive": true
                          },
                          {
                          "_id":"id5",
                          "name":"mod5",
                          "isActive": true,
                            "modules":[
                              {
                              "_id":"id6",
                              "name":"mod6",
                              "isActive": true
                              }
                            ]
                          }
                      ]
                    }
              ]
    }

Course activity collection

   {
    "id":"ca1",
    "studentId:"std1",
    "courseId:"courseId1",
     mProgress:[{
        "id":"ac1",
        "modId":"id5",
        "studentID":"std1",
        "progress":20  
        }
        {
        "id":"ac2",
        "modId":"id4",
        "studentID":"std1",
        "progress":10  
        }
]
}

If I get studentID="std1" , courseId="5f698ca6f5cd3551060d86e8" , moduleId="id3"

I need response link below

modules:
      [
            {
            "modId":"id4",
            "name:"mod4",
            "progress":10  
            },
            {
            "modId":"id5",
            "name:"mod5",
            "progress":0  
            }
      ]
1 Answers

I achieved this by java script. 1st I found course object using mongo query after that I search for nested object(i.e modules array) by using the following function

    findNestedObj(keyToFind, valToFind,obj ) {
      let foundObj;
      JSON.stringify(obj , (_, nestedValue) => {
        if (nestedValue && nestedValue[keyToFind] === valToFind) {
          foundObj = nestedValue;
        }
        return nestedValue;
      });
      return foundObj;
    }

var obj = 'here your object';
findNestedObj('_id','id3',obj );

Then I have calculated % from that

Related