あなたのmongoバイナリが正しくリンクされていると仮定して、このようにJavaアプリケーションからmongoシェルを実行することができます。しかし、代わりにJavaドライバを使用する方が良いでしょう、他の人が言ったように。
あなたがここにコマンドラインからのmongoクエリを実行する詳細については見つけることができます:コメント@felixの答え上記の迅速な応答を https://docs.mongodb.com/v3.2/tutorial/write-scripts-for-the-mongo-shell/
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
// the query you want to run in mongo, you can get it
// from a file using a FileReader
String query = "db.col.find();";
// the database name you need to use
String db = "database";
// run a command from terminal. this line is equivalent to
// mongo database --eval "db.col.find()"
// it calls the mongo binary and execute the javascript you
// passed in eval parameter. It should work for both unix and
// windows
Process pr = rt.exec(new String[]{"mongo", db, "--eval", query});
// read the output of the command
InputStream in = pr.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
// print the command and close outputstream reader
System.out.println(out.toString());
reader.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ありがとう..私のシナリオではjavaドライバを使用してテストします。もっと複雑です。mongoクエリは外部ファイルで作成され、クエリはシェルクエリで記述されています..私のアプリケーションはシェルを読む必要がありますファイルからのクエリと実行..だから私はそれが難しいのJavaベースのクエリには、シェルのクエリを変換する見つける。あなたはこのシナリオに関する任意の提案がありますか? – oxvoxic
この行のパラメータについては、ほとんど説明できません:Process pr = rt.exec(new String [] {"mongo"、db、 "--eval"、query}); – oxvoxic
@oxvoxic私の編集を見て、それが十分明確でないかどうか教えてください! – felix