Mongodb: db.printShardingStatus() / sh.status() call in Java (and JavaScript)

蓝咒 提交于 2019-12-04 17:43:15

Many of the shell's helper functions are not available for server-side code execution. In the case of printShardingStatus(), it makes sense because there isn't a console to use for printing output and you'd rather have a string returned. Thankfully, you should be able to pull up the source of the shell function and reimplement it in your application (e.g. concatenating a returned string instead of printing directly).

$ mongo
MongoDB shell version: 2.2.0
connecting to: test
> db.printShardingStatus
function (verbose) {
    printShardingStatus(this.getSiblingDB("config"), verbose);
}

So, let's look at the printShardingStatus() function...

> printShardingStatus
function (configDB, verbose) {
    if (configDB === undefined) {
        configDB = db.getSisterDB("config");
    }
    var version = configDB.getCollection("version").findOne();

    // ...
}

Before turning all of the output statements into string concatenation, you'd want to make sure the other DB methods are all available to you. Performance-wise, I think the best option is to port the innards of this function to Java and avoid server-side JS evaluation altogether. If you dive deeper into the printShardingStatus() function, you'll see it's just issuing find() on the config database along with some group() queries.

If you do want to stick with evaluating JS and would rather not keep this code within your Java application, you can also look into storing JS functions server-side.

Have you deployed a shard cluster properly? If so, you could connect to a mongo database that has sharding enabled.

Try calling the method db.printShardingStatus() with a that database within the mongo shell and see what happens.

Apparently the Javascript function 'printShardingStatus' is only available for the mongo shell and not for execution with server commands, to see the code start mongo.exe and type only 'printShardingStatus' and press enter.

In this case writing an extension method would be the best for solving this...

Javascript way of printing output of MongoDB query to a file

1] create a javascript file

test.js

cursor = db.printShardingStatus();
while(cursor.hasNext()){
    printjson(cursor.next());
}

2] run

mongo admin --quiet test.js > output.txt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!