'How to execute MongoDB shell command in Java application

I installed 4.4 version MongoDB and reproduced replica set, sharding for my Java application.

Now, I am looking for the approach of run MongoDB shell command in my Java application for check and monitoring reproduced MongoDB Cluster's replica set and sharding status. I'm curious how to achieve this.

I tried to find answers. but, I couldn't found clear answer from other stackoverflow question regarding MongoDB. because most questions discuss base on 3.x version.

So, I researched MongoDB document and driver for 4.4 version and Tested that like below.

  1. run MongoDB command
    • I tried to run "sh.status()" and "rs.status()" command using MongoDB 4.5 driver through MongoClient object and runCommand() method. but, Java return error message.
    • I realized that runCommand() method only allow "Mongo" commands mentioned on below link and not Mongo Shell Command.
      link : https://www.mongodb.com/docs/v4.4/reference/command/
    • I couldn't found contrasting command with sh.status() from above link.
String uriString = "mongodb://"+userName+":"+passWord+"@"+targetHost+":"+portNo;
uriString = uriString +"/?authSource="+tgDBName+"&authMechanism="+authMechanism;

MongoClient mongoClient = MongoClients.create(uriString);

String commandString    = "sh.status()";
Bson command            = new BsonDocument(commandString, new BsonInt64(1));
Document commandResult  = database.runCommand(command);
com.mongodb.MongoCommandException: Command failed with error 59 (CommandNotFound):   
'no such cmd: sh.status()' on server ....
  1. run javascript stored in MongoDB

Finally, I considering access to MongoDB using JSch and run prompt.
But, I think that is not formal approach. so, I want know other way for get metrics
like "run MongoDB Shell Command in java using 4.4 version driver"

Note : when run sh.status() command in mongos, I received metrics successfully like below.

mongos> sh.status()
    --- Sharding Status ---
      sharding version: {
            "_id" : 1,
            "minCompatibleVersion" : 5,
            "currentVersion" : 6,
            "clusterId" : ObjectId("625513e0838da178377f6900")
      }
      shards:
            {  "_id" : "sh01",  "host" : "sh01/WIN-BKEV4AO0KED:27011,WIN-BKEV4AO0KED:27012,WIN-BKEV4AO0KED:27013",  "state" : 1 }
            {  "_id" : "sh02",  "host" : "sh02/WIN-BKEV4AO0KED:27021,WIN-BKEV4AO0KED:27022,WIN-BKEV4AO0KED:27023",  "state" : 1 }
      active mongoses:
            "4.4.13" : 1
      autosplit:
            Currently enabled: yes
      balancer:
            Currently enabled:  yes
            Currently running:  no
            Failed balancer rounds in last 5 attempts:  0
            Migration Results for the last 24 hours:
                    No recent migrations
      databases:
            {  "_id" : "config",  "primary" : "config",  "partitioned" : true }


Solution 1:[1]

rs.status() is a mongo shell helper for db.adminCommand({ replSetGetStatus: 1 })

I don't work with Java, but I guess you must use MongoDatabase.runCommand. Could be similar to this:

MongoDatabase database = mongoClient.getDatabase("admin");
String commandString    = "replSetGetStatus";
Bson command            = new BsonDocument(commandString, new BsonInt64(1));
Document commandResult  = database.runCommand(command);

For sh.status() or db.printShardingStatus() it is a bit more difficult. Documentation says:

The db.printShardingStatus() method run in mongosh does not return JSON. Use db.printShardingStatus() for manual inspection, and Config Database in scripts.

printShardingStatus

function printShardingStatus(configDB, verbose) {
    // configDB is a DB object that contains the sharding metadata of interest.
    // Defaults to the db named "config" on the current connection.
    if (configDB === undefined)
        configDB = db.getSiblingDB('config');

    var version = configDB.getCollection("version").findOne();
    if (version == null) {
        print(
            "printShardingStatus: this db does not have sharding enabled. be sure you are connecting to a mongos from the shell and not to a mongod.");
        return;
    }

    var raw = "";
    var output = function(indent, s) {
        raw += sh._shardingStatusStr(indent, s);
    };
    output(0, "--- Sharding Status --- ");
    output(1, "sharding version: " + tojson(configDB.getCollection("version").findOne()));
    ... many more lines

If you really like to get identical output to db.printShardingStatus(), then you would need to convert the content from that function into Java.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1