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

如何在MongoDB中反转所有集合内的坐标顺序?

批量反转MongoDB所有集合中的地理坐标顺序

你的数据里location.coordinates的顺序不符合MongoDB Point类型规范(MongoDB要求为**[经度, 纬度]**,当前数据是[纬度, 经度]),可以用以下MongoDB Shell脚本批量修正所有集合中的坐标:

// 遍历所有集合,反转符合条件的坐标
db.getCollectionNames().forEach(function(collectionName) {
  const coll = db.getCollection(collectionName);
  // 更新所有Point类型且坐标为长度2的数组的文档
  coll.updateMany(
    { 
      "location.type": "Point", 
      "location.coordinates": { $exists: true, $type: "array", $size: 2 } 
    },
    [
      {
        $set: {
          "location.coordinates": { $reverseArray: "$location.coordinates" }
        }
      }
    ]
  );
  // 输出处理结果
  print(`已处理集合: ${collectionName}, 成功更新 ${coll.getLastErrorObj().nModified} 条文档`);
});

注意事项

  • 执行操作前务必备份数据,防止意外情况
  • 如果只需处理特定集合,把db.getCollectionNames()换成指定集合数组,比如["skateparks"]
  • 该脚本需要MongoDB 3.4及以上版本支持($reverseArray操作符的最低版本要求)

内容的提问来源于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 09:10:30