Efan Du
Efan Du

Reputation: 123

MongoDB Convert String to Array

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.

Upvotes: 4

Views: 11107

Answers (3)

Raghav salotra
Raghav salotra

Reputation: 870

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

Upvotes: 6

Efan Du
Efan Du

Reputation: 123

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

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88378

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

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

Upvotes: 3

Related Questions