Search code examples
javamongodbmongo-java

how to execute mongo admin command from java


I want to execute soem admin command with parameters from java.

The commands are:

{ enablesharding : "test" }
{ shardcollection : "test.test_collection", key : {"number":1} }

How can I do it from java driver?

The following code doesn't works:

mongo.getDb("admin").command("{shardcollection : \"test.test_collection\", key:\"number\":1} }")

Solution

  • I just found it

    DB db = mongo.getDB("admin");
    DBObject cmd = new BasicDBObject();
    cmd.put("shardcollection", "testDB.x");
    cmd.put("key", new BasicDBObject("userId", 1));
    CommandResult result = db.command(cmd);