Here's a suggestion you can try:
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);
});
To convert the document into the desired format, you can utilize the MongoDB aggregation framework. Use the $addFields
, $regexFind
, and $convert
operators to extract, transform, and load new fields.
Below is an aggregation pipeline that can help achieve the desired outcome:
db.collection.aggregate([
{ $addFields: {
userAddressList: {
$let: {
vars: {
street: {
$regexFind: { input: "$address", regex: /(\w+)\s+Street/ }
},
house: {
$regexFind: { input: "$address", regex: /house\s+(\d+)/ }
},
appartment: {
$regexFind: { input: "$address", regex: /appartment\s+(\d+)/ }
},
floor: {
$regexFind: { input: "$address", regex: /floor\s+(\d+)/ }
}
},
in: [
{
street: "$$street.match",
house: "$$house.match",
building: "",
appartment: {
$convert: {
input: "$$appartment.match",
to: "long",
onError: NumberLong(0),
}
},
entrance: NumberLong(0),
floor: {
$convert: {
input: "$$floor.match",
to: "long",
onError: NumberLong(0)
}
},
intercom: ""
}
]
}
}
} },
{ $project: { address: 0 } }
]);