codeofnode
codeofnode

Reputation: 18609

why shardCollection command not working in mongo shell script

i am trying to execute the following command within mongo shell script :

sh.shardCollection('mydb.collection', { shardKey : 1 });

but it does not do anything.

However When i execute from script :

print(sh.help())

I get all the help options.

So means 'sh' variable is also availabe in mongo shell script.

then why i can't execute shardCollection though the mongo shell script?

EDIT : Thanks to neil for his comments.. Here is my mongo shell script

db = connect("mydb");
print(db.help());

var cols = db.getCollectionNames();

var names = [
  'a',
  'b',
  'c'
];


var forEachCol = function(i){
  if(i === cols.length) return print('Sharding on collections Succesfull');
  if(names.indexOf(cols[i]) !== -1) {
    sh.shardCollection(cols[i], { shardKey : 1 });
  }
  forEachCol(i+1);
};

forEachCol(0);

Each of the documents in each collections a,b,c have a field 'shardKey' (with index). So 'shardKey' help to keep documents with a specific shardKey on one shard.

now when i go to mongo shell and run

db.printShardingStatus()

I get the output as

{  "_id" : "mydb",  "partitioned" : false,  "primary" : "shard0000" }

and sharding for no collection being listed here. Means the sh.shardCollection not working.

Upvotes: 0

Views: 4824

Answers (1)

John Petrone
John Petrone

Reputation: 27487

You are using the command incorrectly. The correct usage is to pass sh.shardCollection() both the name of the database and collection and a document describing the shard key. For example:

sh.shardCollection("myDatabaseName.MyCollectionName", {"myshardkey":1})

You name the name space as a combination of the database name and the collection name separated by a period. The shardkey document should be the key in the collection that you want to use as a shard key. If you wanted to the shard key to be hashed you would use {"myshardkey":"hashed"} instead.

Please note that your script cannot work as designed. In order to shard your collections you need to pass in the desired shard key and this will generally not be something a script that loops thru all collections will be able to determine automatically. Sometimes it will be "_id" but sometimes it will be another field or group of fields - it all depends on what you choose to use as a key.

I would strongly urge you to read up on sharding in general - it's not a trivial process to do it well.

http://docs.mongodb.org/manual/reference/method/sh.shardCollection/#sh.shardCollection

http://docs.mongodb.org/manual/core/sharding-introduction/

Upvotes: 1

Related Questions