Add new field with value from existing one in mongoDb

Viewed 19

I am trying to add new fields to my existing collection. The collection look like this.

{
  "_id": {
    "$oid": "62df66945e2ecab37dd56a69"
  },
  "AllApplicableSteps": [
    {
      "StepName": "Open",
      "StepNo": 1,
      "StepDesc": "Open Step"
    },
    {
      "StepName": "Pending",
      "StepNo": 1,
      "StepDesc": "Pending Step"
    },
    {
      "StepName": "Approved",
      "StepNo": 3,
      "StepDesc": "successful"
    },
    {
      "StepName": "Rejected",
      "StepNo": 3,
      "StepDesc": "rejected"
    }
  ]
}

My goal is to add another field name like "StepTitle" which value will be the same as " StepName"

{
  "_id": {
    "$oid": "62df66945e2ecab37dd56a69"
  },
  "AllApplicableSteps": [
    {
      "StepName": "Open",
      "StepTitle": "Open",
      "StepNo": 1,
      "StepDesc": "Open Step"
    },
    {
      "StepName": "Pending",
      "StepTitle": "Pending",
      "StepNo": 1,
      "StepDesc": "Pending Step"
    },
    {
      "StepName": "Approved",
      "StepTitle": "Approved",
      "StepNo": 3,
      "StepDesc": "successful"
    },
    {
      "StepName": "Rejected",
      "StepTitle": "Rejected",
      "StepNo": 3,
      "StepDesc": "rejected"
    }
  ]
}

In the aggregation pipeline I am trying with $set

{
  "AllApplicableSteps.StepTitle" : "$AllApplicableSteps.StepName"
}

enter image description here

But above pipeline return an array of all stepName. EG. enter image description here

1 Answers

You want to be using $map to iterate over the array and transform each object independently, like so:

db.collection.aggregate([
  {
    $addFields: {
      AllApplicableSteps: {
        $map: {
          input: "$AllApplicableSteps",
          in: {
            "$mergeObjects": [
              "$$this",
              {
                StepTitle: "$$this.StepName"
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Related