Andy
Andy

Reputation: 1231

Mongodb Geospatial index does not support $box?

I am creating a 2dsphere index and trying to utilize it for my geospatial queries. However, I find when I use $geoWithin.$box, it does not use the index, hence, very slow. If I use $geoWithin.$geometry, then the index will be used. The document says $box supports index, so I must be miss something. Any idea?

Geospatial Index

    {
            "v" : 1,
            "key" : {
                    "details.lonlat" : "2dsphere"
            },
            "name" : "longlat",
            "ns" : "realestate.property",
            "2dsphereIndexVersion" : 2
    }

Query with GeoJSON polygon uses the index

> db.property.find({'details.lonlat': {'$geoWithin': {$geometry: {type:'Polygon', coordinates: [[[1,1],[2,2],[3,3], [1,1]]]}}}}).explain()

"inputStage" : {
                                        "stage" : "IXSCAN",
                                        "keyPattern" : {
                                                "details.lonlat" : "2dsphere"
                                        },
...

Using $box does not use index, but collection scan (why?)

> db.property.find({'details.lonlat': {'$geoWithin': {'$box': [[ 0, 0 ], [ 100, 100 ] ]}}}).explain()
            "winningPlan" : {
                    "stage" : "COLLSCAN",
                    "filter" : {
                            "details.lonlat" : {
                                    "$geoWithin" : {
                                            "$box" : [
                                                    [
                                                            0,
                                                            0
                                                    ],
                                                    [
                                                            100,
                                                            100
                                                    ]
                                            ]
                                    }
                            }
                    },
                    "direction" : "forward"

Mongodb Info

            "version" : "3.0.4",
            "gitVersion" : "0481c958daeb2969800511e7475dc66986fa9ed5"

Upvotes: 4

Views: 707

Answers (1)

odedfos
odedfos

Reputation: 4619

The 2dsphere does not support $box query. That's why your query falls to a full collection scan.

The box documentation states the following:

Only the 2d geospatial index supports $box

Adding a 2d index should do the trick, something like:

db.property.ensureIndex({"details.lonlat": "2d"});

Upvotes: 7

Related Questions