Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 
    ... 
  }],
  ...
}
like image 572
MrSingh Avatar asked Jan 28 '26 09:01

MrSingh


2 Answers

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.

like image 104
rickhg12hs Avatar answered Jan 30 '26 08:01

rickhg12hs


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.

like image 31
MrSingh Avatar answered Jan 30 '26 08:01

MrSingh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!