【问题标题】:exception: geoNear command failed: errmsg: more than one 2d index异常:geoNear 命令失败:errmsg:多个二维索引
【发布时间】:2019-09-16 10:13:45
【问题描述】:

我正在尝试按距离从集合中检索文档。我尝试使用 $geoNear 聚合,但我遇到错误(使用 node.js 和邮递员)或返回 0 条记录。

示例文档:

{
    "_id" : ObjectId("5cc37692fe9fd54b3cd136c9"),
    "category" : "art",
    "description" : "an eastbound description for The soda event.",
    "geometry" : {
        "type" : "Point",
        "coordinates" : [ 
            3.60178480057443, 
            6.46123057784917
        ]
    }
    "__v" : 0
}
.
.

型号:

const GeoSchema = new Schema({
  type: {
    type: String,
    default: "Point"
  },
  coordinates: {
    type: [Number],
    index: "2dsphere"
  }
}, { _id: false });

const EventSchema = new Schema({
  category: String,
  description: String,
  geometry: GeoSchema,
});

查询

db.events.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [3.60178480057443, 6.46123057784917] },
        distanceField: "dist",
        maxDistance: 90000,
        spherical: true
     }
   }
]);

运行上面的查询返回零个结果,一个空数组(在邮递员上),有时会显示这个错误:

{
    "name": "MongoError",
    "errmsg": "exception: geoNear command failed: { ok: 0.0, errmsg: \"more than one 2d index, not sure which to run geoNear on\" }",
    "code": 16604,
    "ok": 0
}

当显示此错误时,我运行db.events.dropIndex 函数。我复制并粘贴了文档中使用的示例,效果很好。请问如何使这个 $geoNear 函数工作。我已经为此苦苦挣扎了一整天。

【问题讨论】:

    标签: javascript mongodb mongoose geometry aggregation-framework


    【解决方案1】:

    单个集合不能有多个2dsphere 索引,并且您通过运行以下命令在多个字段上创建了2dsphere 索引。

    db.getCollection('test').createIndex({ "loc": "2dsphere" }) 
    

    所以删除索引之一,它就会工作。您可以使用此检查索引列表

    db.getCollection('test').getIndexes()
    

    更新:

    如果您的集合有多个$geoNear 索引,您可以使用key 参数指定要在哪个字段上进行搜索

    【讨论】:

      猜你喜欢
      • 2019-01-19
      • 2011-01-14
      • 2016-09-30
      • 2013-05-01
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多