如何执行MONGO从Java管理命令(how to execute mongo admin comm

2019-06-24 02:33发布

我想从Java参数来执行SOEM管理命令。

这些命令是:

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

我怎样才能做到这一点从Java驱动程序?

下面的代码不工作:

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

Answer 1:

我只是觉得

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);


Answer 2:

我只想补充一点的Julia的回答是正确的,但现在它已过时。 你可以使用新的API( Document类是包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)));


Answer 3:

你确保你已经验证成功的分贝?

您是否尝试过db.eval(COMMAND_THAT_YOU_WANT_TO_EVAL);



文章来源: how to execute mongo admin command from java