Search code examples
jsonmongodbtype-conversion

MongoDB: convert existing json string to json object


I am trying to convert an existing json string field to json array/object as I have recently moved data from mysql to mongodb.

{
  "_id": {
    "$oid": "63f241012a9551202e909257"
  },
  "title": "Jumanji: Welcome To The Jungle",
  "description": "...",
  ...
  "info": "[{\"year\": \"2017\", ... },{\"year\": \"2019\", ... }]",
  ...
}

I need this to be

{
  "_id": {
    "$oid": "63f241012a9551202e909257"
  },
  "title": "Jumanji: Welcome To The Jungle",
  "description": "...",
  ...
  "info": [{
    "year": 2017, 
    ... 
  }, {
    "year": 2019, 
    ... 
  }],
  ...
}

Solution

  • Here's one way to convert your JSON string by letting Javascript parse it.

    db.movies.update({},
    [
      {
        "$set": {
          "info": {
            "$function": {
              "lang": "js",
              "args": ["$info"],
              "body": "function(infoStr) {return JSON.parse(infoStr)}"
            }
          }
        }
      }
    ],
    {
      "multi": true
    })
    

    Try it on mongoplayground.net.