Reputation: 123
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
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
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
Reputation: 88378
You simply need to apply JSON.parse
to each of these strings:
> JSON.parse("[\"502\",\"784\",\"1060\"]")
[ '502', '784', '1060' ]
Upvotes: 3