如何在MongoDB中将字符串转换为数组? [英] How to convert String to Array in MongoDB?

查看:760
本文介绍了如何在MongoDB中将字符串转换为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当对象类型更改时,我会陷入困境。

I'm stuck at the situation when the type of an object was changed.

我该如何转换:

{ 
"_id" : NumberLong(257),
"address" : "street  Street, house 50, appartment 508, floor 5"
}

为此:

{ 
"_id" : NumberLong(257),
 "userAddressList" : [{
        "street" : "Street",
        "house" : "50",
        "building" : "",
        "appartment " : NumberLong(508),
        "entrance" : NumberLong(0),
        "floor" : NumberLong(5),
        "intercom" : ""
    }]
}

使用mongo shell吗?

using mongo shell?

我需要转换大约350个条目,希望可以通过脚本完成。

I need to convert about 350 entries, hope it can be done by the script.

推荐答案

您可以尝试以下操作:

db.collection.find().forEach( function (x) {   
    lines = x.address.split(",");
    obj = {};
    userAddressList = [];
    lines.forEach( function (address){
        addressArray = address.replace(/^\s\s*/, '').replace(/\s\s*$/, '').split(" ");
        obj[addressArray[0]] = !isNaN(parseInt(addressArray[1])) ? parseInt(addressArray[1]) : addressArray[1];        
    });
    obj.building = "";
    obj.intercom = "";
    userAddressList.push(obj);
    x.userAddressList = userAddressList; // convert field to string
    db.collection.save(x);
});

这篇关于如何在MongoDB中将字符串转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆