Reputation: 4614
What is the syntax for setting a shard key from the MongoDB Java Driver version 2.10.1?
Or to put it another way, how do I do this w/ the Java Driver?
sh.shardCollection("test.a", {"_id": "hashed"}})
Upvotes: 3
Views: 4507
Reputation: 91
For setting the sharding via Java api's:
CommandResult result=null;
// The only way to shard this is via executing a command. If this is not
// done the collection will becreated but it will not be
// sharded. The first arg is the key and the second one is the logic to be used
final BasicDBObject shardKey = new BasicDBObject("_id", "hashed");
final BasicDBObject cmd = new BasicDBObject("shardCollection", "test."+collectionName);
cmd.put("key", shardKey);
// RUnning the command to create the sharded collection
result = mongoClient.getDB("admin").command(cmd);
System.out.println("Collection created successfully");
// loading the collection and then will be insterting the data
final DBCollection shardCollection = mongoClient.getDB("test").getCollection(collectionName);
// Here i am using a arraylist values which has all the data
shardCollection.insert(values);
System.out.println("Collection added");
Upvotes: 1
Reputation: 12240
Short answer: you should issue a shardCollection
command.
Long answer:
The sh.shardCollection
in MongoDB shell is just a helper method for calling a command on admin
db.
If you enter sh.shardCollection
in the MongoDB shell you will see what this function is actually doing:
> sh.shardCollection
function ( fullName , key , unique ) {
sh._checkFullName( fullName )
assert( key , "need a key" )
assert( typeof( key ) == "object" , "key needs to be an object" )
var cmd = { shardCollection : fullName , key : key }
if ( unique )
cmd.unique = true;
return sh._adminCommand( cmd );
}
You can then call sh._adminCommand
in the MongoDB shell:
> sh._adminCommand
function ( cmd , skipCheck ) {
if ( ! skipCheck ) sh._checkMongos();
return db.getSisterDB( "admin" ).runCommand( cmd );
}
When you put all together, all the sh.shardCollection
command is doing is checking parameters and calling this command:
db.getSisterDB( "admin" ).runCommand({
shardCollection : "test.a" ,
key : {"_id": "hashed"}
});
Java Syntax:
DBObject cmd = new BasicDBObject("shardCollection", "test.a").
append("key",new BasicDBObject("_id", "hashed"));
CommandResult r = db.getSisterDB("admin").command(cmd);
Upvotes: 9
Reputation: 6233
There isn't an API for that. You'll have to issue a command to set that shard key.
Upvotes: -1