我正在尝试在 mongo shell 脚本中执行以下命令:
sh.shardCollection('mydb.collection', { shardKey : 1 });
但它什么也没做。
但是,当我从脚本执行时:
print(sh.help())
我得到了所有的帮助选项。
所以意味着 'sh' 变量也可以在 mongo shell 脚本中使用。
那为什么我不能通过 mongo shell 脚本执行 shardCollection 呢?
编辑:感谢尼尔的评论.. 这是我的 mongo shell 脚本
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);
每个集合中的每个文档a,b,c
都有一个字段“shardKey”(带索引)。因此,“shardKey”有助于将具有特定 shardKey 的文档保存在一个分片上。
现在当我去 mongo shell 并运行时
db.printShardingStatus()
我得到的输出为
{ "_id" : "mydb", "partitioned" : false, "primary" : "shard0000" }
并在此处列出没有集合的分片。表示sh.shardCollection
不工作。