Search code examples
mongodbindexinggeolocationgeospatialdatabase

$near query returns 0 results after adding $maxDistance


I have a database with structure like this :

{
    "_id" : ObjectId("5785663bda7b71a0c5601c89"),
    "visible" : true,
    "created" : {
        "changeset" : "29670315",
        "user" : "samit_53",
        "version" : "1",
        "uid" : "2297171",
        "timestamp" : "2015-03-23T03:59:14Z"
    },
    "type" : "node",
    "id" : "3413812873",
    "pos" : [
        22.1173487,
        88.0034742
    ]
}

Now I have '2d' index on pos

>>db.kol_sample.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "project_sample.kol_sample",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
            "pos" : "2d"
        },
        "ns" : "project_sample.kol_sample",
        "name" : "pos_2d"
    }
]

Now when I query with only the $near I get 100 results

db.kol_sample.findOne({"pos":{$near:[22,88]}})
{
    "_id" : ObjectId("5785663bda7b71a0c5601c89"),
    "visible" : true,
    "created" : {
        "changeset" : "29670315",
        "user" : "samit_53",
        "version" : "1",
        "uid" : "2297171",
        "timestamp" : "2015-03-23T03:59:14Z"
    },
    "type" : "node",
    "id" : "3413812873",
    "pos" : [
        22.1173487,
        88.0034742
    ]
}

But after I add the $maxDistance param no matter what distance I pass it always returns null

db.kol_sample.findOne({"pos":{$near:[22.1173487,88.0034742]},$maxDistance:100})
null

MongoDB shell version: 2.4.9 32bit


Solution

  • I was using a wrong syntax where I need to pass $maxDistance in the dictionary passed to the pos

    Wrong

    db.kol_sample.find({"pos":{$near:[22.1173487,88.0034742]},$maxDistance:100})
    

    Correct

    db.kol_sample.find({pos:{$near:[22.1173487,88.0034742],$maxDistance:1/111.2}})