如何在MongoDB中将String转换为Array

How to convert String to Array in MongoDB?

本文关键字:转换 Array String 中将 MongoDB      更新时间:2023-09-26

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

如何转换:

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

我需要转换大约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 } }
]);

您可以在更新中使用foreach,如以下

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