4

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 3

6

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)});
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

1

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); 
});

1 Comment

No need to remove the brackets literals, use JSON.parse on the current Answers value as suggested by @RayToal below db.Question.find({}).snapshot().forEach(function (el) { el.Answers = JSON.parse(el.Answers); db.Question.save(el); });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.