Search code examples
mongodbinsertgeojson2dsphere

mongoldb insert does the property order matters?


I have a collection with the following indices.

[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "bs.locations"
    },
    {
        "v" : 1,
        "key" : {
            "location" : "2dsphere"
        },
        "name" : "location_2dsphere",
        "ns" : "bs.locations",
        "2dsphereIndexVersion" : 2
    }
]

I can insert the following document:

db.locations.insert({ "location" : {"coordinates" : [ 6.982654547382455, 46.88414220428685 ], "type" : "Point", "test":1.0} })

but when I try to insert this document:

db.locations.insert({ "location" : {"test":1.0, "coordinates" : [ 6.982654547382455, 46.88414220428685 ], "type" : "Point"} })

i get the following error:

WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 16755,
        "errmsg" : "Can't extract geo keys: { _id: ObjectId('5566050507c10c31ce7214af'), location: { test: 1.0, coordinates: [ 6.982654547382455, 46.88414220428685 ], type: \"Point\" } }  Point must only contain numeric elements"
    }
})

My question is, what do I miss here? What is my error?

I use MongoDB version v3.0.1


Solution

  • According to MongoDB manual There are some field restrictions on 2dsphere indexing. The restrictions are given as following :

    2dsphere Indexed Field Restrictions Fields with 2dsphere indexes must hold geometry data in the form of coordinate pairs or GeoJSON data. If you attempt to insert a document with non-geometry data in a 2dsphere indexed field, or build a 2dsphere index on a collection where the indexed field has non-geometry data, the operation will fail.

    To be a GeoJSON object an object should contain type and coordinates fields according to following structure :

    { type: "<GeoJSON type>" , coordinates: <coordinates> }
    

    As location is indexed as 2dsphere your first insert query get satisfied because it contains the pair at the beginning of the document. But in the case of the second one the document structure is violating the restrictions. It expects either type or coordinates from the beginning.

    According to MongoDB manual this is the only logical reason behind the situation of your insert statement.