How to convert String to Array in MongoDB?

核能气质少年 提交于 2019-12-24 13:41:39

问题


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

How can I convert this:

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

to this:

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

using mongo shell?

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


回答1:


You could try this:

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



回答2:


you can use a foreach in the update like this

db.test.find( { } ).forEach( function (x) {
x.userAddressList = x.address.split(" "); db.test.save(x); });



来源:https://stackoverflow.com/questions/29500874/how-to-convert-string-to-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!