Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 977
Efan Du Avatar asked Nov 02 '25 08:11

Efan Du


1 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)});
like image 104
Raghav salotra Avatar answered Nov 03 '25 23:11

Raghav salotra