Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} }")
like image 342
Julias Avatar asked May 01 '12 07:05

Julias


2 Answers

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);
like image 90
Julias Avatar answered Oct 14 '22 02:10

Julias


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)));
like image 24
Vasyl Sarzhynskyi Avatar answered Oct 14 '22 03:10

Vasyl Sarzhynskyi