如何在MongoDB中将String转换为Array?

w1e3prcc  于 2023-04-20  发布在  Go
关注(0)|答案(2)|浏览(259)

当一个对象的类型被改变的时候,我被卡住了。
我如何转换它:

{ 
"_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个条目,希望它可以由脚本完成。

p8ekf7hl

p8ekf7hl1#

你可以试试这个:

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

rsaldnfx2#

您可以在更新中使用foreach,如下所示
db.test.find( { } ).forEach( function (x) { x.userAddressList = x.address.split(" "); db.test.save(x); });

相关问题