mongodb type_error ai_generated true

MongoServerError:无法将地理索引与非地理查询过滤器一起使用:期望字段 'location' 为 GeoJSON 对象

MongoServerError: Can't use geo index with non-geo query filter: expected field 'location' to be a GeoJSON object

ID: mongodb/geo-index-with-non-geo-query

其他格式: JSON · Markdown 中文 · English
88%修复率
86%置信度
1证据数
2024-03-05首次发现

根因分析

字段上存在 2dsphere 或 2d 索引,但查询过滤器在同一字段上使用了非地理空间操作符(如 $eq、$regex),导致类型不匹配。

English

A 2dsphere or 2d index exists on a field, but the query filter uses a non-geospatial operator (e.g., $eq, $regex) on the same field, causing type mismatch.

generic

官方文档

https://www.mongodb.com/docs/manual/core/index-geospatial/

解决方案

  1. Ensure the field contains valid GeoJSON data (e.g., {type: 'Point', coordinates: [lng, lat]}) and use geospatial operators like $geoWithin in the query. Example: db.places.find({location: {$geoWithin: {$centerSphere: [[-73.97, 40.77], 0.01]}}})
  2. If the field is not geospatial, drop the geo index and create a regular index (e.g., db.collection.createIndex({location: 1})), then use non-geo queries.

无效尝试

常见但无效的做法:

  1. 85% 失败

    Removing the geo index entirely bypasses the error but degrades geospatial query performance; the error returns if the index is recreated.

  2. 80% 失败

    Changing the query to use $geoWithin or $near without converting the field data to GeoJSON format still fails with a similar error.