首页 > 解决方案 > 在 mongo shell 中使用 JavaScript 将字符串拆分为对象

问题描述

在我的 mongo 集合中,我有一个字符串范围 =“2000 - 3000 INR”,现在我想将此字符串分解为一个对象范围 = { min: 2000, max: 3000, currency: "INR"} 我的集合看起来像:

{
  "id": "ABC",
  "places": [
    {
      "isSearchable": true,
      "locations": [
        {
          "id": "DEL",
          "loc": {
            "range": "2000-5000 INR"
          }
        },
        {
          "id": "BLG",
          "loc": {
            "range": "1000-3000 INR"
          }
        }
      ]
    }
  ]
}

我知道我们可以在 mongo shell 中编写 javascript 函数,但我不知道如何继续。我写了这样的东西:

cursor = db.getCollection('locations').find({"places.isSerachable":true});



// Iterate over Cursor object
while(cursor.hasNext()) {
item = cursor.next();
keys = Object.keys(item);

// Iterate over MongoDB doc fields
for (i=0; i-keys.length; i++) {
let field = keys[i];
print( "field:", field, "---",item[keys[i]]);
}

}

感谢您的帮助!

标签: javascriptmongodbmongodb-query

解决方案


试试这个解决方案:

const obj = {
  "id": "ABC",
  "places": [{
    "isSearchable": true,
    "locations": [{
        "id": "DEL",
        "loc": {
          "range": "2000-5000 INR"
        }
      },
      {
        "id": "BLG",
        "loc": {
          "range": "1000-3000 INR"
        }
      }
    ]
  }]
}
const result = obj.places.map(x => ({
  ...x,
  locations: x.locations.map(y => ({
    ...y,
    loc: {
      range: (() => {
        [min, max, currency] = y.loc.range.replace('-', ' ').split(' ');
        return {
          min,
          max,
          currency
        }

      })()
    }
  }))
}))

console.log(result)


推荐阅读