Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
Run my mongodb command from java program

How to run multiple mongodb commands from a java code. I need the mongodb commands to get executed in background when i run the java program. This program throws some exception "Exception in thread "main" java.io.IOException: Cannot run program "db.createCollection("employ")": error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) . . .".

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class try1
{

    public static void main(String[] args) throws Exception{

        String command ="mongo";
        String command1="db.createCollection(\"employ\")";
        Process proc = Runtime.getRuntime().exec(command);
        Process proc1 = Runtime.getRuntime().exec(command1);

        BufferedReader reader =  
              new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = "";
        while((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }
        proc.waitFor();   

        BufferedReader reader1 =  
              new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line1 = "";
        while((line1 = reader1.readLine()) != null) {
            System.out.print(line1 + "\n");
        }
        proc1.waitFor(); 
    }
}

I need to run a set of mongo db commands from the java program. The program works with other terminal commands like "ls"(only single command). But there is problem if we give both command1 and command as "ls". Only one ls command gets executed. If trying with only one mongo db command say, "mongo" command does not get executed completely(program does not terminate). Is it because of "proc.waitFor()".

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

i got the code. db.eval() function serves my purpose. It works perfectly. :) "query" is the String which stores the mongodb query.

 public  void qexecute()
        {
        try{String query="db.products.insert( { item: "card", qty: 15 } )";
              MongoClient mongo = new MongoClient("localhost",27017);
              DB db = mongo.getDB("test");
              DBCollection collection = db.getCollection(tablename);  
              db.eval(query);   
             }
          catch(UnknownHostException e){
              System.out.println(e);
           }
           catch (MongoException.DuplicateKey e) {
              System.out.println("Exception Caught" + e);
           }
    }
over 4 years ago · Santiago Trujillo Relatório

0

I strongly recommend to use Mongo Spring Data. You can do that:

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBCollection {

public static void main(String args[]) {

    try {

        //Connect to Database
        MongoClient mongoClient = new MongoClient("localhost",27017);
        DB db = mongoClient.getDB("myDB");
        System.out.println("Your connection to DB is ready for Use::"+db);

        //Create Collection
        DBCollection linked = db.createCollection("employ",new BasicDBObject()); 
        System.out.println("Collection employ created successfully");

    } catch(Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

}

}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda