MongoDB 将字符串转换为数组 [英] MongoDB Convert String to Array
本文介绍了MongoDB 将字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 MongoDB 非常陌生,在将数据导入数据库时遇到了一些困难.现在我有一个看起来像
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"],
}
知道怎么做吗?谢谢.
推荐答案
您可以使用 JSON.parse() 将字符串类型更改为列表,然后使用更新元素保存集合.下面是一个例子:
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)});
这篇关于MongoDB 将字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文