需要有 2d 和 2dsphere 索引,但不能创建这两个索引。为什么?

Need to have 2d and 2dsphere indexes, but can't create those two indexes. Why?

在对 MongoDB 地理数据查询进行单元测试时,我收到以下错误消息:

can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { address.location: { $nearSphere: { x: -120.0, y: 47.0 }, $maxDistance: 0.01567855942887398 }, status: "INIT" }; nested exception is com.mongodb.MongoException: can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { address.location: { $nearSphere: { x: -120.0, y: 47.0 }, $maxDistance: 0.01567855942887398 }, status: "INIT" }

在 运行 createIndex 命令之后,我得到以下错误:

db.store.createIndex({"address.location":"2d"}) location object expected, location array not in correct format db.store.createIndex({"address.location":"2dsphere"}) Can't extract geo keys from object, malformed geometry?:{ type: "Point", coordinates: [ 47.399465, -122.2950165 ] }

文档数据结构如下:

{
 ....
       "address" : {
           "street" : "Street One",
           "city" : "One City",
           "province" : "aProvince",
           "country" : "aCountry",
           "postalCode" : "91202",
           "location" : {
                   "type" : "Point",
                   "coordinates" : [
                           47.5891279,
                           -122.0446183
                   ]
           }
   }

我做错了什么?

看起来你的 "longitude" 和 "latitude" 的顺序相反,错误应该告诉你一口井(至少在 3.x 系列中是这样)。你有 "latitude" 和 "longitude",所以反转它:

{
   "address" : {
       "street" : "Street One",
       "city" : "One City",
       "province" : "aProvince",
       "country" : "aCountry",
       "postalCode" : "91202",
       "location" : {
           "type" : "Point",
           "coordinates" : [
               -122.0446183,
               47.5891279
           ]
       }
    }
}

并且索引创建没有错误:

db.store.ensureIndex({ "address.location": "2dsphere" })

这是一个"2dsphere" index. A "2d" index cannot be created on a GeoJSON对象,所以你只能直接使用"coordinates":

db.store.ensureIndex({ "address.location.coordinates": "2d" })

它是 "planar",因此 GeoJSON 格式不适用。