【问题标题】:Unable to find index for $geoNear Laravel找不到 $geoNear Laravel 的索引
【发布时间】:2018-10-28 12:04:31
【问题描述】:

我在 Laravel 5.6 中使用 Moloquent 模型。以下是我的收藏记录:-

{
    "_id" : ObjectId("5afe619dbe0b8d0e5876b16b"),
    "name" : "Central Park",
    "categories" : [ 
        "4d4b7105d754a06376d81259", 
        "4bf58dd8d48988d116941735", 
        "4bf58dd8d48988d119941735", 
        "4d4b7105d754a06376d81259", 
        "4bf58dd8d48988d116941735", 
        "4bf58dd8d48988d119941735", 
        "4d4b7105d754a06374d81259", 
        "4bf58dd8d48988d16d941735"
    ],
    "loc" : {
        "type" : "Point",
        "coordinates" : [ 
            88.4166612820784, 
            22.5835157504658
        ]
    }
}

我从 Laravel 控制器运行这个查询。

$users = MongoTest::where('loc', 'near', [
                    '$geometry' => [
                        'type' => 'Point',
                        'coordinates' => [
                            $longitude,
                            $latitude,
                        ],
                    ],
                    '$maxDistance' => 10,
                ])->get();

print_r($users);

我收到此错误:-

error processing query: ns=tkit.testTree: GEONEAR  field=loc maxdist=10 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query

我该如何解决这个问题?

【问题讨论】:

  • 当然是通过创建地理空间索引。该错误告诉您您没有索引,"loc" 字段上需要有一个索引。
  • 你能建议怎么做吗,我的意思是结构?我是 MongoDB 新手

标签: php mongodb laravel moloquent


【解决方案1】:

从 mongo shell 创建一个索引。使用$near$nearSphere 运算符或geoNear 命令,甚至$geoNear 聚合管道阶段的查询需要2sphere index

createIndex() 方法将为您执行此操作,因此只需在正确的数据库中命名您的集合:

db.collection.createIndex({ "loc": "2dsphere" })

请注意,任何实际使用 geoNear 命令的 API 确实需要更新为其他提到的查询运算符之一,因为从 MongoDB 4.0 开始,该命令已“弃用”并将被删除。

寻找“最近”的操作应该使用$near$nearSphere,而那些想要返回“距离”的操作应该使用$geoNear pipelie 阶段。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2014-06-05
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2015-01-06
    • 1970-01-01
    相关资源
    最近更新 更多