Home > Net >  Adding parent field value in subdocuments while concating
Adding parent field value in subdocuments while concating

Time:08-03

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

CodePudding user response:

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

  • Related