how to execute mongo admin command from java
Asked Answered
D

3

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} }")
Deaf answered 1/5, 2012 at 7:40 Comment(0)
D
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);
Deaf answered 1/5, 2012 at 7:52 Comment(2)
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.Omentum
mongo.getDb("admin").runCommand would have been more intuitive.Parliamentarian
T
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)));
Tang answered 1/11, 2017 at 19:34 Comment(1)
How can you tell if the return Document was successful or not? The CommandResult has an OK method on it. Document does notAnette
T
-1

Have you ensured you have authenticated to the db successfully?

Have you tried db.eval(COMMAND_THAT_YOU_WANT_TO_EVAL);

Trixy answered 1/5, 2012 at 7:52 Comment(3)
db.eval() has two arguments. I do not know what Objects... args should beDeaf
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.Trixy
Keep in mind this does not work in sharded environmentsEurasian

© 2022 - 2024 — McMap. All rights reserved.