Home > Software design >  How to remove same property name from sub object and push the sub objects as element of an array in
How to remove same property name from sub object and push the sub objects as element of an array in

Time:10-26

The coursesMarks property is present in every object. So I want to push the value inside coursesMarks property, to an array and return the array to the user.

[
        {
            "coursesMarks": {
                "_id": "634a9be567a1f07be02f71d8",
                "courseCode": "cse1201",
                "courseTitle": "SP"
            }
        },
        {
            "coursesMarks": {
                "_id": "634a9be567a1f07be02f71db",
                "courseCode": "cse1203",
                "courseTitle": "DS"
                
            }
        }
]

Then expected output is:

[
{

     "courses":
                {
                        "_id": "634a9be567a1f07be02f71d8",
                        "courseCode": "cse1201",
                        "courseTitle": "SP"
                },
                {
                        "_id": "634a9be567a1f07be02f71db",
                        "courseCode": "cse1203",
                        "courseTitle": "DS"
                }
    
}
]

CodePudding user response:

I've asked a clarifying question in the comments. But if we assume that the sample data provided is a single document where the array is stored in a field named arr, then a pipeline similar to the following may be what you are looking for:

[
  {
    $addFields: {
      courses: {
        $map: {
          input: "$arr",
          in: "$$this.coursesMarks"
        }
      }
    }
  },
  {
    $unset: "arr"
  }
]

Playground example here


Edit

Based on the additional information about the structure of the data, you are looking to $group things in this particular case. Therefore the relevant addition to your pipeline should look something like this:

[
  ...
  {
    $group: {
      _id: null,
      courses: {
        $push: "$coursesMarks"
      }
    }
  },
  {
    $unset: "_id"
  }
]

Playground demonstration here. It includes an empty $match stage at the beginning to represent whatever additional matching logic you currently have.

  • Related