Changing string to object

I want to make a migration to update all old data. Old data has this structure:

error: [
  "error1",
  "error2",
  "error3",
]

I would like to change to:

error: [
 { message: "error1", status: 400 },
 { message: "error2", status: 400 },
  { message: "error3", status: 400 },
]

Could you give me any hints or pointers to make the query? Thanks

Hello,

You can use $map and change each member to a document.
Bellow its the aggregation pipeline query.

Data in

[{"error": [
  "error1",
  "error2",
  "error3",
]}]

Query

aggregate(
[ {
  "$set" : {
    "error" : {
      "$map" : {
        "input" : "$error",
        "in" : {
          "message" : "$$this",
          "status" : 400
        }
      }
    }
  }
} ]
)

Data out

[{
  "error": [
    {
      "message": "error1",
      "status": 400
    },
    {
      "message": "error2",
      "status": 400
    },
    {
      "message": "error3",
      "status": 400
    }
  ]
}]
1 Like

thanks, it works. although i change it to updateMany instead of aggregate

oh ok good, i didn’t see its for update, but update pipeline would work, MongoDB documentation is very good with examples also.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.