MongoDB Convert String to Array

Viewed 9137

I'm very new to MongoDB and experience some difficulties in importing data into the database. Now I have a collection of documents which looks like

db.Question.findOne()
{
"_id" : ObjectId("124"),
"Answers" : "[\"502\",\"784\",\"1060\"]",
}

The Answers are now stored as a single string. However I want to convert it to a list like below so I could unwind it when doing query.

  {
    "_id" : ObjectId("124"),
    "Answers" : ["502","784","1060"],
    } 

Any idea how to do it ? Thanks.

3 Answers

You can use JSON.parse() to change string type to list and then save the collection with update element. Below is a example:

db.Question.find({}).snapshot().forEach(function (el){el.Answers=JSON.parse(el.Answers);db.Question.save(el)});

You simply need to apply JSON.parse to each of these strings:

> JSON.parse("[\"502\",\"784\",\"1060\"]")
[ '502', '784', '1060' ]

First remove "[" and "]" in the data, then use below code, which create a new attribute,answers, which is a array/list that holds individual numbers:

db.Question.find({}).snapshot().forEach(function (el) {
    el.answers=el.Answers.substring(1,el.Answers.length-1);     
    el.answers = el.Answers.split(',');  
         db.Question.save(el); 
});
Related