英文:
MongoDB: convert existing json string to json object
问题
我正在尝试将现有的json字符串字段转换为json数组/对象,因为我最近将数据从mysql迁移到mongodb。
我需要将这样的内容转换为:
{
  "_id": {
    "$oid": "63f241012a9551202e909257"
  },
  "title": "Jumanji: Welcome To The Jungle",
  "description": "...",
  // ...
  "info": [
    {
      "year": 2017,
      // ...
    },
    {
      "year": 2019,
      // ...
    }
  ],
  // ...
}
英文:
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, 
    ... 
  }],
  ...
}
答案1
得分: 2
这里有一种将您的JSON字符串转换为JavaScript parse 的方法。
db.movies.update({},
[
  {
    "$set": {
      "info": {
        "$function": {
          "lang": "js",
          "args": ["$info"],
          "body": "function(infoStr) {return JSON.parse(infoStr)}"
        }
      }
    }
  }
],
{
  "multi": true
})
在mongoplayground.net上尝试它。
英文:
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](https://mongoplayground.net/p/orfsnRSSifq "Click me!").
答案2
得分: 0
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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论