mongodbsharding

Unable to shard an already populated collection in mongodb


I ran the command to shard on the collection using this command

sh.shardCollection("db.collection_name",{"_id":"hashed"})

I got the following error

{
    "ok" : 0.0,
    "errmsg" : "Please create an index that starts with the proposed shard key before sharding the collection",
    "code" : 72,
    "codeName" : "InvalidOptions",
    "operationTime" : Timestamp(1582011118, 65),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1582011118, 65),
        "signature" : {
            "hash" : { "$binary" : "jOIjTJkZKkC2ZI5lFQwX4Q7QNfs=", "$type" : "00" },
            "keyId" : NumberLong(6774859010160984065)
        }
    }
}

There is already an index on _id

    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "db.collection_name"
    }

I am running Mongo 4.0.0 sharded cluster setup


Solution

  • If you are sharding already populated collection. Then you should try :

    I have database test and collection name as people. Basically you need to create an index in order to shard already populated collection. Select the key from collection and hash it

    mongos> db.people.createIndex({ "user_id" : "hashed" }) /// 
                                        db.collection.createIndex({ "key" : "hashed"})
    {
            "raw" : {
                    "foo/localhost:27017,localhost:27018,localhost:27019" : {
                            "createdCollectionAutomatically" : false,
                            "numIndexesBefore" : 4,
                            "numIndexesAfter" : 5,
                            "ok" : 1
                    }
            },
            "ok" : 1,
            "operationTime" : Timestamp(1593154931, 1),
            "$clusterTime" : {
                    "clusterTime" : Timestamp(1593154931, 1),
                    "signature" : {
                            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                            "keyId" : NumberLong(0)
                    }
            }
    
    
    mongos> sh.shardCollection("test.people", { "user_id": "hashed" })
    {
            "collectionsharded" : "test.people",
            "collectionUUID" : UUID("4ee30d04-8dc9-43dc-94f6-a898bc96da89"),
            "ok" : 1,
            "operationTime" : Timestamp(1593154958, 11),
            "$clusterTime" : {
                    "clusterTime" : Timestamp(1593154958, 11),
                    "signature" : {
                            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                            "keyId" : NumberLong(0)
                    }
            }
    }
    
    mongos> sh.isBalancerRunning()
    

    true

    Hope it helps!!