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.

Community
  • 1
  • 1
Max Charas
  • 4,980
  • 3
  • 20
  • 40
  • You can just do that but in Java using the: http://docs.mongodb.org/manual/reference/command/isMaster/ command – Sammaye Sep 03 '13 at 13:28
  • I want to use the Java drivers :) – Max Charas Sep 03 '13 at 13:28
  • 2
    Yeah, and database commands are callable from the Java Driver, they are just different to find, try this question: http://stackoverflow.com/questions/10394917/how-to-execute-mongo-admin-command-from-java – Sammaye Sep 03 '13 at 13:29
  • Nice! Copy paste that as a response and I'll approve it! :) – Max Charas Sep 03 '13 at 13:37

1 Answers1

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.

Dyin
  • 5,815
  • 8
  • 44
  • 69