Reputation: 1231
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?
{
"v" : 1,
"key" : {
"details.lonlat" : "2dsphere"
},
"name" : "longlat",
"ns" : "realestate.property",
"2dsphereIndexVersion" : 2
}
> 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"
},
...
> 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"
"version" : "3.0.4",
"gitVersion" : "0481c958daeb2969800511e7475dc66986fa9ed5"
Upvotes: 4
Views: 707
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