How to do a bounding box query with MongoDB?

Viewed 1372

I can't seem to get a bounding box query working with MongoDB, that actually uses the spatial index.

Here's my indexes:

[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "config.Listings"
    },
    {
        "v" : 2,
        "key" : {
            "LatLong" : "2dsphere"
        },
        "name" : "LatLong_2dsphere",
        "ns" : "config.Listings",
        "2dsphereIndexVersion" : 3
    },
    {
        "v" : 2,
        "key" : {
            "ListingId" : 1
        },
        "name" : "ListingId",
        "ns" : "config.Listings"
    },
    {
        "v" : 2,
        "key" : {
            "Category" : 1,
            "Status" : 1
        },
        "name" : "Category_and_Status",
        "ns" : "config.Listings"
    },
    {
        "v" : 2,
        "key" : {
            "Category" : 1,
            "Status" : 1,
            "Suburb" : 1
        },
        "name" : "Basic_Suburb_Search",
        "ns" : "config.Listings"
    },
    {
        "v" : 2,
        "key" : {
            "LatLong.Coordinates" : "2d"
        },
        "name" : "LatLong.Coordinates_2d",
        "ns" : "config.Listings"
    }
]

I initially just had the 2dsphere index, but then i saw this answer saying box queries only work with 2d indexes.

When i try the box query, it doesn't seem to use either index:

db.Listings.find( {
   LatLong: { $geoWithin: { $box:  [ [ 144.9941034, -37.8220633 ], [ 145.0551353, -37.79494 ] ] } }
} ).explain()

It does return results, but does a COLLSCAN and is very slow.

I've also tried this:

db.Listings.find( {
   "LatLong.coordinates": { $geoWithin: { $box:  [ [ 144.9941034, -37.8220633 ], [ 145.0551353, -37.79494 ] ] } }
} )

Same result - returns data but does a COLLSCAN.

LatLong is a GeoJSON object. Here's an example document:

{
    "_id" : ObjectId("5bd64f2274cb40f172a328fb"),
    "LatLong" : {
        "type" : "Point",
        "coordinates" : [ 
            151.2504, 
            -33.96767
        ]
    },
    // other props removed for simplicity
}

Can someone tell me what i'm doing wrong?

0 Answers
Related