mongodbreducetypegoose

Adding parent field value in subdocuments while concating


I want to add parent field value inside its subDocs

I want task name inside all of its subdocuments. Example document:

  {
    _id: 1,
    tasks: [
      {
        _id: 1,
        assigned: [
          {
            _id: 1,
            name: "assigned1",
            solutions: [
              {_id: 1, name: "solution 1"},
              {_id: 2, name: "solution 2"}
            ]
          },
          {
            _id: 2,
            name: "assigned2",
            solutions: [
              {_id: 1, name: "solution 1"},
              {_id: 2, name: "solution 2"}
            ]
          }
        ]
      }
    ]
  }

Below is Necessary data related to this question

Mongo PlayGround


Solution

  • If I understand correctly, you want to use $map and $mergeObjects for three hierarchies:

    db.collection.aggregate([
      {
        $set: {
          tasks: {
            $map: {
              input: "$tasks",
              as: "task",
              in: {
                $mergeObjects: [
                  "$$task",
                  {
                    assigned: {
                      $map: {
                        input: "$$task.assigned",
                        as: "assigned",
                        in: {
                          $mergeObjects: [
                            "$$assigned",
                            {
                              solutions: {
                                $map: {
                                  input: "$$assigned.solutions",
                                  as: "solution",
                                  in: {
                                    $mergeObjects: [
                                      "$$solution",
                                      {
                                        taskName: "$$assigned.name"
                                      }
                                    ]
                                  }
                                }
                              }
                            }
                          ]
                        }
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    ])
    

    See how it works on the playground example