2

Is it possible to ask a MongoDB host if it is the master using the Java drivers?

I've checked the issue Ask MongoDB if it is Master out of a bashscript but I'd rather try to do this in my application rather than wiring in a bash script.

4
  • You can just do that but in Java using the: docs.mongodb.org/manual/reference/command/isMaster command Commented Sep 3, 2013 at 13:28
  • I want to use the Java drivers :) Commented Sep 3, 2013 at 13:28
  • 2
    Yeah, and database commands are callable from the Java Driver, they are just different to find, try this question: stackoverflow.com/questions/10394917/… Commented Sep 3, 2013 at 13:29
  • Nice! Copy paste that as a response and I'll approve it! :) Commented Sep 3, 2013 at 13:37

1 Answer 1

1

Maybe there is no helper function provided for the Java Driver, but still, you can issue commands with the driver.

If you go into the MongoDB Shell, and print

db.isMaster (without the parenthesis)

and hit enter, the JavaScript interpreter will print out the implementation of the helper function. On db context, the isMaster() function is a helper, with the following code:

function () { return this.runCommand("isMaster"); }

So in the background db.runCommand("isMaster") performed. There are a lot of helpers in the Mongo Shell, some of them are fairly complicated and simplifies your everyday work on administration.

You can do the same in the Java Driver with the following method on an object of class DB:

CommandResult command(DBObject cmd, int options, ReadPreference readPrefs, DBEncoder encoder) Executes a database command.

CommandResult command(String cmd, int options) Executes a database command.

So there is no need to construct a DBObject for the command, just pass the string: "isMaster". Anticipate a CommandResult object and proceed as you will.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.