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,
...
}],
...
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With