skip to Main Content

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, 
    ... 
  }],
  ...
}

2

Answers


  1. Chosen as BEST ANSWER

    With reference to @rickhg12hs solution, below is another way to perform the same task.

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

    Also, please keep that in mind that the arrow function syntax is not supported in this scenario. So, always use function notations to perform such operations.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search