You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB中所有地理位置坐标从字符串转换为浮点数?

将MongoDB中parks集合的coordinates字符串转换为浮点数

你可以使用MongoDB的updateMany()方法结合聚合管道批量处理所有文档,把location.coordinates数组中的字符串元素转为浮点数:

db.parks.updateMany(
  {}, // 匹配集合内所有文档
  [
    {
      $set: {
        "location.coordinates": {
          $map: {
            input: "$location.coordinates",
            as: "coord",
            in: { $toDouble: "$$coord" }
          }
        }
      }
    }
  ]
);

代码说明:

  • updateMany({}, [...]):第一个空对象表示匹配所有文档,第二个参数是聚合管道,用于执行更新逻辑
  • $map:遍历location.coordinates数组的每一个元素
  • $toDouble:将字符串类型的坐标值转换为浮点数
  • $set:把转换后的数组重新赋值给location.coordinates字段

执行完成后,可通过db.parks.findOne()验证结果,coordinates内的元素会变为浮点数类型。

内容的提问来源于stack exchange,提问作者chovy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:05:24