Search code examples
mongodbsharding

Can not use indexed key(_id) as a sharding key in mongodb


I am a newbie of mongodb,here is a simple case but got an error:

I want to use _id field (generated and indexed automatically) as a sharding key in mongodb, but got this error.

{
"proposedKey" : {
    "_id" : "hashed"
},
"curIndexes" : [
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "jackfruit.scenicspots"
    },
    {
        "v" : 1,
        "key" : {
            "geoLocation" : "2dsphere"
        },
        "name" : "geoLocation_2dsphere",
        "ns" : "jackfruit.scenicspots",
        "2dsphereIndexVersion" : 2
    }
],
"ok" : 0,
"errmsg" : "please create an index that starts with the shard key before sharding."

}

the error message showed that I already have an Index named _id_ on key _id, why the error still occur?


Solution

  • I found an answer from manual.

    MongoDB does not support creating new unique indexes in sharded collections and will not allow you to shard collections with unique indexes on fields other than the _id field.

    And here is a solution:

    fromEnforce Unique Keys for Sharded Collections