如何在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
相关产品推荐
相关产品推荐

