Om du får ett "longitud/latitud is out of bounds"-fel när du försöker skapa ett 2dsphere-index i MongoDB, kan det bero på att dina longitud- och latitudkoordinater är i fel ordning.
När du skapar ett GeoJSON-objekt måste du först lista longituden och sedan latituden.
- Giltiga longitudvärden är mellan
-180och180, både inklusive. - Giltiga latitudvärden är mellan
-90och90, både inklusive.
Därför, om du får felet "longitud/latitud is out of bounds", kontrollera dina dokument för att se i vilken ordning koordinaterna för latitud och longitud är.
Exempel på fel
Här är ett exempel på en samling som heter bars som innehåller dokument med koordinater i fel ordning.
{
"_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
]
}
}
Om vi försöker skapa ett 2dsphere-index på location fältet får vi ett felmeddelande.
Exempel:
db.bars.createIndex(
{ location : "2dsphere" }
) Resultat:
{
"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"
} Exempel med korrekt koordinatordning
Här är samlingen igen, förutom med koordinaterna i rätt ordning:
{
"_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
]
}
}
Låt oss nu skapa ett 2dsphere-index på location fält:
db.bars.createIndex(
{ location : "2dsphere" }
) Resultat:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
} Det betyder att den skapades.
Vi kan kontrollera detta med getIndexes() metod:
db.bars.getIndexes() Resultat:
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"location" : "2dsphere"
},
"name" : "location_2dsphere",
"2dsphereIndexVersion" : 3
}
]