MongoDB: 将现有的 JSON 字符串转换为 JSON 对象

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月19日 23:54:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定