5.1 Geospatial indexes

Not all forms of query require the creation of a geospatial index, but even when the index is not mandatory, it can improve query performance.

MongoDB works with geospatial data in the form of pairs of coordinates, refered as legacy, and GeoJSON objects, where the type field specifies the type of the object and coordinates specifies the coordinates of the object.

In collection pages, the coordinates field contains coordinate pairs (legacy), while the geometry field contains GeoJSON objects.

Two geospatial indexes will then be created, a 2d index for the coordinates field, and a 2dsphere index for the geometry field, as shown bellow:

> db.pages.createIndex( { coordinates: "2d" } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}
> db.pages.createIndex( { geometry: "2dsphere" } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 3,
        "numIndexesAfter" : 4,
        "ok" : 1
}
>

To display the existing indexes was used the method:

> db.pages.getIndexes();
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "reficio.pages"
        },
        {
                "v" : 2,
                "key" : {
                        "_fts" : "text",
                        "_ftsx" : 1
                },
                "name" : "title_text_content_text_slug_text",
                "ns" : "reficio.pages",
                "weights" : {
                        "content" : 1,
                        "slug" : 1,
                        "title" : 1
                },
                "default_language" : "english",
                "language_override" : "language",
                "textIndexVersion" : 3
        },
        {
                "v" : 2,
                "key" : {
                        "coordinates" : "2d"
                },
                "name" : "coordinates_2d",
                "ns" : "reficio.pages"
        },
        {
                "v" : 2,
                "key" : {
                        "geometry" : "2dsphere"
                },
                "name" : "geometry_2dsphere",
                "ns" : "reficio.pages",
                "2dsphereIndexVersion" : 3
        }
]
>

5. Geospatial queries