Mongodb sharding collection

mongodbsharding

Im trying to shard my collection. when I execute the command:

sh.enableSharding("testdb")

I get:

{
    "ok" : 1,
    "operationTime" : Timestamp(1552083125, 2),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1552083125, 2),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}

Now when I try to shard my collection with the command: "sh.shardCollection("testdb.testcollection", {testkey:1})"

I get the error:

{
    "ok" : 0,
    "errmsg" : "Cannot accept sharding commands if not started with --shardsvr",
    "code" : 193,
    "codeName" : "NoShardingEnabled",
    "operationTime" : Timestamp(1552083136, 4),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1552083136, 4),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}

I checked the status of the shard and it looks like it was successful:

sh.status()
--- Sharding Status --- 
  sharding version: {
    "_id" : 1,
    "minCompatibleVersion" : 5,
    "currentVersion" : 6,
    "clusterId" : ObjectId("5c82df7b7a98360e9dd3c5da")
  }
  shards:
        {  "_id" : "shard0000",  "host" : "127.0.0.1:27023",  "state" : 1 }
        {  "_id" : "shard0001",  "host" : "127.0.0.1:27024",  "state" : 1 }
  active mongoses:
        "4.0.6" : 1
  autosplit:
        Currently enabled: yes
  balancer:
        Currently enabled:  yes
        Currently running:  no
        Failed balancer rounds in last 5 attempts:  0
        Migration Results for the last 24 hours: 
                No recent migrations
  databases:
        {  "_id" : "config",  "primary" : "config",  "partitioned" : true }
        {  "_id" : "testdb",  "primary" : "shard0000",  "partitioned" : true,  "version" : {  "uuid" : UUID("ed327ab3-1de9-4a0a-89f5-8d0bf81015fc"),  "lastMod" : 1 } }

So why do I get that error when I try to shardCollection? I running all of this in the mongos instance

Best Answer

If a replicaset needs to be added as shard in a sharded cluster, --shardsvr argument is mandatory when starting a mongod process.

mongod --shardsvr --replSet <replSetname>  --dbpath <path> --bind_ip localhost,<hostname(s)|ip address(es)>

If is it a config server, then --configsvr argument is mandatory

mongod --configsvr --replSet <replica set name> --dbpath <path> --bind_ip localhost,<hostname(s)|ip address(es)>

Refer the following link to deploy

Deploy a Sharded Cluster