Search code examples
mongodb2dsphere

2dsphere index query returns all documents


I'm using MongoDB 2.6.1 on Mac OS X

I have a collection of locations with a valid GeoJSON field:

db.locations.findOne({}, {"location": 1})
{
1"_id" : ObjectId("534fd2b6b13e51768cd0e9c8"),
"location" : {
    "type" : "Point",
    "coordinates" : [
        41.311,
        56.3526
    ]
}
}

I have 2dsphere index in my database:

db.locations.getIndexes()
[   
{
    "v" : 1,
    "key" : {
        "location" : "2dsphere"
    },
    "ns" : "insta_locations.locations",
    "name" : "location_2dsphere"
},
...
]

But when I query locations without a hint I get an error:

db.locations.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [41.311, 56.35]
            },
            $maxDistance: 1
        }
    }
})

produces:

error: { "$err" : "can't find special index: 2d for: { location: { $near: { $geometry: { type: \"Point\", coordinates: [ 41.311, 56.35 ] }, $maxDistance: 1.0 } } }", "code" : 13038 }

On the other hand with the hint it returns the whole collection:

db.locations.find({
    location: {
        $near: {
            $geometry: {
                type: "Point",
                coordinates: [41.311, 56.35]
            }, 
            $maxDistance: 1
        }
    }
}).hint('location_2dsphere').length()

5138

Does anyone knows what am I missing to make it work properly?

Update

> version()
2.6.1
> db.version()
2.2.2

Solution

  • You are running the mongo shell from version 2.6.1 but still have a mongod version from 2.2.2. This can happen on a Mac OS X installation when you've been using homebrew, macports or a combination of the two. Basically the mongod that is first in your path is not the latest version. To correct I'd try the following:

    1. Find out where mongo and mongod are running from by running "which mongo" and "which mongod".
    2. Check your path by running "echo $PATH"
    3. Locate the correct mongod file.
    4. Change path in your profile to search the correct directory for mongod first.

    Or, you could just use the full path to the correct mongod when starting mongodb.

    Or, you could just download it again directly from mongodb.