9

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} }")
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
Julias
  • 5,752
  • 17
  • 59
  • 84

3 Answers3

16

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);
Julias
  • 5,752
  • 17
  • 59
  • 84
  • This answer was useful for me. I'll just point that I needed to connect to a `mongos`, a simple `mongod` is not enough. It may be obvious but I didn't saw it here explicitly. – jmmut Dec 16 '15 at 16:47
  • 1
    `mongo.getDb("admin").runCommand` would have been more intuitive. – Alexander Suraphel Sep 01 '16 at 06:43
10

I just want to add that Julias's answer is correct, but now it's deprecated. You could use new API (Document class is from package org.bson):

MongoDatabase database = client.getDatabase("admin");
Document documentA = database.runCommand(new Document("enablesharding", "test"));
Document documentB = database.runCommand(
        new Document("shardcollection", "testDB.x").append("key", new Document("userId", 1)));
Vasyl Sarzhynskyi
  • 3,689
  • 2
  • 22
  • 55
  • How can you tell if the return Document was successful or not? The CommandResult has an OK method on it. Document does not – Karl May 05 '20 at 05:46
-1

Have you ensured you have authenticated to the db successfully?

Have you tried db.eval(COMMAND_THAT_YOU_WANT_TO_EVAL);

user1367351
  • 102
  • 2