gpt4 book ai didi

javascript - 如何在 MongoDB 中将字符串转换为数组?

转载 作者:行者123 更新时间:2023-11-30 12:25:38 29 4
gpt4 key购买 nike

当对象的类型发生变化时,我陷入了困境。

我如何转换它:

{ 
"_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 外壳?

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

最佳答案

你可以试试这个:

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 聚合框架将给定文档转换为所需格式。您需要使用 $addFields$regexFind$convert 运算符来提取、转换和加载新字段。

以下聚合管道应该会为您提供所需的结果:

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

关于javascript - 如何在 MongoDB 中将字符串转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29500874/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com