Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set shard key with MongoDB Java Driver

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"}})
like image 657
Bob B Avatar asked Dec 21 '25 01:12

Bob B


2 Answers

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);
like image 78
Christian P Avatar answered Dec 22 '25 16:12

Christian P


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");
like image 36
RandomGuy Avatar answered Dec 22 '25 17:12

RandomGuy