javascript - 在 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]]);
}
}
感谢您的帮助!
解决方案
试试这个解决方案:
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)
推荐阅读
- python - Python正则表达式库是否有最大匹配
- java - Kotlin 标准库中的 String 类是如何实现的?
- python - Python 如何进行主机名查找?
- python - 基于具有相同值对但在两个数据框中以不同顺序显示的两列合并熊猫数据框
- amazon-web-services - 我无法获取 ALB URL。地址为空
- snowflake-cloud-data-platform - 如何在不丢失或复制任何记录的情况下移动或更改管道
- javascript - 验证数组中的几个对象的干净方法是什么?
- google-cloud-platform - GCP Marketplace 基本映像
- javascript - 检查是否使用javascript按下按钮
- .net-core - dotnet run 和 dotnet watch run 在 MacOS 上启动有时需要一分钟以上