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} }")

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
mongo.getDb("admin").runCommand would have been more intuitive.
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)));

1 Comment

How can you tell if the return Document was successful or not? The CommandResult has an OK method on it. Document does not
-1

Have you ensured you have authenticated to the db successfully?

Have you tried db.eval(COMMAND_THAT_YOU_WANT_TO_EVAL);

3 Comments

db.eval() has two arguments. I do not know what Objects... args should be
You might want to take a closer look @Julias. The second argument is a variable length argument list; this means is can be zero or more arguments.
Keep in mind this does not work in sharded environments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.