phpmongodblaravelmoloquent

Unable to find index for $geoNear Laravel


I am using the Moloquent model with Laravel 5.6. here is my collection record given below:-

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

I am running this query from the Laravel controller.

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

print_r($users);

I am getting this error:-

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

How can I solve this?


Solution

  • Create an index from the mongo shell. A 2sphere index is expected by the query using the $near or $nearSphere operator or geoNear command, or even the $geoNear aggregation pipeline stage.

    The createIndex() method will do this for you, so just name your collection within the correct database:

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

    Note that any API actually using the geoNear command really needs to update to one of the other mentioned query operators as this command is "deprecated" from MongoDB 4.0 onwards and will be removed.

    Operations looking for "nearest" should use $near or $nearSphere, and those which want to return the "distance" should use the $geoNear pipelie stage instead.