Fix “longitude/latitude is out of bounds” in MongoDB when Creating a 2dsphere Index

If you’re getting a “longitude/latitude is out of bounds” error when trying to create a 2dsphere index in MongoDB, it could be due to your longitude and latitude coordinates being in the wrong order.

When you create a GeoJSON object, you need to list the longitude first and then latitude.

  • Valid longitude values are between -180 and 180, both inclusive.
  • Valid latitude values are between -90 and 90, both inclusive.

Therefore, if you’re getting the “longitude/latitude is out of bounds” error, check your documents to see which order the latitude and longitude coordinates are in.

Example of Error

Here’s an example of a collection called bars that contains documents with coordinates in the wrong order.

{
	"_id" : 1,
	"name" : "Boardwalk Social",
	"location" : {
		"type" : "Point",
		"coordinates" : [
			-16.919297718553366,
			145.77675259719823
		]
	}
}
{
	"_id" : 2,
	"name" : "The Downunder Bar",
	"location" : {
		"type" : "Point",
		"coordinates" : [
			-16.92107838010542,
			145.77621640842125
		]
	}
}

If we try to create a 2dsphere index on the location field, we’ll get an error.

Example:

db.bars.createIndex( 
    { location : "2dsphere" }
)

Result:

{
	"ok" : 0,
	"errmsg" : "Index build failed: 2bb26869-1dec-4484-b554-3ba55fc0c0de: Collection krankykranes.bars ( e1a99ee2-b77c-41a4-b833-25c4b3c599c3 ) :: caused by :: Can't extract geo keys: { _id: 1.0, name: \"Boardwalk Social\", location: { type: \"Point\", coordinates: [ -16.91929771855337, 145.7767525971982 ] } }  longitude/latitude is out of bounds, lng: -16.9193 lat: 145.777",
	"code" : 16755,
	"codeName" : "Location16755"
}

Example with Correct Coordinate Order

Here’s the collection again, except with the coordinates in the correct order:

{
	"_id" : 1,
	"name" : "Boardwalk Social",
	"location" : {
		"type" : "Point",
		"coordinates" : [
			145.77675259719823,
			-16.919297718553366
		]
	}
}
{
	"_id" : 2,
	"name" : "The Downunder Bar",
	"location" : {
		"type" : "Point",
		"coordinates" : [
			145.77621640842125,
			-16.92107838010542
		]
	}
}

Now let’s create a 2dsphere index on the location field:

db.bars.createIndex( 
    { location : "2dsphere" }
)

Result:

{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

This means that it was created.

We can check this with the getIndexes() method:

db.bars.getIndexes()

Result:

[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_"
	},
	{
		"v" : 2,
		"key" : {
			"location" : "2dsphere"
		},
		"name" : "location_2dsphere",
		"2dsphereIndexVersion" : 3
	}
]