13
votes

I have a collection in MongoDB with a 2dsphere index. The object I want to save looks like this:

{
        "type" : "Polygon",
        "coordinates" : [ 
            [ 
                [ 
                    5.052617929724351, 
                    52.64653192570052
                ], 
                [ 
                    5.051738165167465, 
                    52.64765805672784
                ], 
                [ 
                    5.054162882116928, 
                    52.64831549553909
                ], 
                [ 
                    5.054592035559312, 
                    52.64780777138566
                ], 
                [ 
                    5.055364511755601, 
                    52.64790541110375
                ], 
                [ 
                    5.056094072607651, 
                    52.64688343792051
                ], 
                [ 
                    5.054237983969346, 
                    52.64661654927096
                ], 
                [ 
                    5.052617929724351, 
                    52.64653192570052
                ]
            ]
        ]
    }

According to http://geojsonlint.com/ this is perfectly valid GeoJSON. However MongoDB says it can't extract the geo keys because the GeoJSON might be malformed.

Can anyone help me out and spot the mistake?

This is the MongoDB error I get:

insertDocument :: caused by :: 16755 Can't extract geo keys from object, malformed geometry?
1
You have 2 arrays brackets around your point arrays. Try removing one set of the array brackets. Should be [[lat, long],[lat, long],...] - Brian Shamblen
Hello Brian, I don't think this is correct. A Polygon in GeoJSON is an array of coordinate rings. GeoJSON lint also reports that this is invalid GeoJSON. I'll give it a try in MongoDB though. - Mathyn
Sorry. I thought only MultiPolygon needed the extra array brackets. So funny... I found a post with the answer that started the same exact way groups.google.com/forum/m/#!topic/mongodb-user/OPouYFHS_zU - Brian Shamblen
No problem :) It's an easy mistake to make. - Mathyn
that's not the issue at all, this exact document works just find as a value of a geoJSON object in your document. - Asya Kamsky

1 Answers

2
votes

The problem is that you are not providing the name of the top level object that the GeoJSON would be assigned to.

You must have created the "2dsphere" index on the "coordinates" field. Instead you want to create it on the field that this entire GeoJSON value will be assigned to.

db.geo.createIndex({"location":"2dsphere"})
db.geo.insert({"location" : {
     "type" : "Polygon",
     "coordinates" : [
        [ <list of your-coord-pairs> ]
     ]
 }})
WriteResult({ "nInserted" : 1 })