throwing an error while trying to convert the data types in mongoshell

Viewed 31

I created a database named as database and a collection called Netflix. there is a field in the database called "genres" which was of type string I need to change the data type to the array. I am trying to use the below command in the mongo shell but it's throwing an error.

db.netflix.find({}).forEach(function(x){x.genres=JSON.parse(x.genres); db.netflix.save(x); })
**Error:**
TypeError: db.netflix.save is not a function

below pic shows how the data in genres field looks like

below pic shows how the data in genres field looks like

2 Answers

Here's one way to let the MongoDB server do all the work by using a pipeline in an update.

N.B.: I have little regex-foo so there is a better regex. E.g., if an element of "genres" (between quotes) contains a comma, the "regex" below won't be sufficient. Also note that I needed to escape " with \ in the "regex" - you may, or may not need to do this.

db.collection.update({
  "genres": {
    "$type": "string"
  }
},
[
  {
    "$set": {
      "genres": {
        "$map": {
          "input": {
            "$regexFindAll": {
              "input": "$genres",
              "regex": "(?<=\")[^,]*?(?=\")"
            }
          },
          "as": "elem",
          "in": "$$elem.match"
        }
      }
    }
  }
],
{
  "multi": true
})

Try it on mongoplayground.net. (Modified sample document from MongoDB Atlas documentation.)

Starting in MongoDB 4.2, the db.collection.save() method is deprecated. Use db.collection.insertOne() or db.collection.replaceOne() instead.

for the above query , you can try, this works:

db.netflix.find({}).forEach(function(x){x.genres= JSON.parse(x.genres); db.netflix.replaceOne({id:x.id},x); });

Related