2

I would like to get Kevin pub spots near a given position. Here is the userSpots collection :

{   user:'Kevin',
    spots:[
        {   name:'a',
            type:'pub',
            location:[x,y]
        },
        {   name:'b',
            type:'gym',
            location:[v,w]
        }
    ]
},
{   user:'Layla',
    spots:[
        ...
    ]
}

Here is what I tried :

db.userSpots.findOne(
    {   user: 'Kevin',
        spots: { 
            $elemMatch: {
                location:{ $nearSphere: [lng,lat], $maxDistance: d},
                type: 'pub'
                }
            }
        },
    },
    function(err){...}
)

I get a strange error. Mongo tells me there is no index :2d in the location field. But when I check with db.userSpots.getIndexes(), the 2d index is there. Why doesn't mongodb see the index ? Is there something I am doing wrong ?

MongoError: can't find special index: 2d for : { spots: { $elemMatch: { type:'pub',location:{ $nearSphere: [lng,lat], $maxDistance: d}}}, user:'Kevin'}

db.userSpots.getIndexes() output :

    {
    "0" : {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "mydb.userSpots",
        "name" : "_id_"
    },
    "1" : {
        "v" : 1,
        "key" : {
            "spots.location" : "2d"
        },
        "ns" : "mydb.usersBoxes",
        "name" : "spots.location_2d",
        "background" : true,
        "safe" : null
    }
}

2 Answers 2

2

For a similar geospatial app, I transformed the location into GeoJSON:

{
    "_id" : ObjectId("5252cbdd9520b8b18ee4b1c3"),
    "name" : "Seattle - Downtown",  
    "location" : {
        "type" : "Point",
        "coordinates" : [
           -122.33145,
            47.60789
         ]
   }
}

(the coordinates are in longitude / latitude format. Mongo's use of GeoJSON is described here.).

The index is created using:

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

In my aggregation pipeline, I find matches using:

{"$match":{"location":{"$geoWithin": {"$centerSphere":[[location.coordinates[0], location.coordinates[1]], radius/3959]}}}}

(where radius is measured in miles - the magic number is used to convert to radians).

Sign up to request clarification or add additional context in comments.

Comments

0

To index documents containing array of geo data MongoDB uses multi-key index. Multi-key index unwinds document to some documents with single value instead of array before indexing. So the index consider that key field as single value field not array.

Try query it without $elemMatch operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.