2

I'm able to export an entire collection using Mongoexport command in the Mongo shell.

But, I'm trying to write a java program which uses a Mongoexport command to export entire collection of MongoDB into a CSV file.

My code:

public class MongoExportSample {
    public static void main(String[] args) {

         String db = "pack";
         String col = "col";
         String Host="localhost";
         String Port="27017";
         String fileName = "D:/user/sample.csv";
         String command = "mongoexport --host Host --port Port --db " + db + " --collection " + col + " --csv --out " + fileName + "";

         try {
             Process process=Runtime.getRuntime().exec(command);
             int waitFor = process.waitFor();
             System.out.println("waitFor:: "+waitFor);
             BufferedReader success=new BufferedReader(new InputStreamReader(process.getInputStream()));
             BufferedReader error=new BufferedReader(new InputStreamReader(process.getErrorStream()));

             String s="";
             while ((s = success.readLine()) != null) {
             System.out.println(s);
             }

             while ((s = error.readLine()) != null) {
             System.out.println("Std ERROR : " + s);
             }
             } catch (Exception e) {
             e.printStackTrace();
             }
    }
}

I'm facing java.io.IOException: Cannot run program "mongoexport": CreateProcess error=2, The system cannot find the file specified.

Can anyone please help me out regarding the same ...

Please check the screenshot for STDERR here

2
  • Are you using Mongo 3.4? Just to improve the syntax of the export command. Commented May 15, 2017 at 12:55
  • I'm using Mongo 3.2 Commented May 15, 2017 at 12:57

1 Answer 1

2

Here is the updated code to suppress the warnings, included the fields that need to be exported (this is mandatory for CSV mode) and added the absolute path to mongoexport.exe.

public static void main(String[] args) {

        String db = "pack";
        String col = "col";
        String Host = "localhost";
        String Port = "27017";
        String fileName = "D:/files/sample.csv";

        String command = "C:\\Program Files\\MongoDB\\Server\\3.4\\bin\\mongoexport.exe --host " + Host + " --port " + Port + " --db " + db + " --collection " + col + " --type=csv --fields _id,email,createdAt, --out " + fileName + "";

        try {
            System.out.println(command);
            Process process = Runtime.getRuntime().exec(command);
            int waitFor = process.waitFor();
            System.out.println("waitFor:: " + waitFor);
            BufferedReader success = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            String s = "";
            while ((s = success.readLine()) != null) {
                System.out.println(s);
            }

            while ((s = error.readLine()) != null) {
                System.out.println("Std ERROR : " + s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Debug Notes:-

In case if you hit up with any problem, please first check whether the command is valid and then try it in the Java program.

Example:-

mongoexport.exe --host localhost --port 27017 --db test --collection Account --csv --out D:/files/sample.csv    

Alternate solution using ProcessBuilder:-

I have set processBuilder.redirectErrorStream(true) to true. So, you will get all the process message in one stream.

public static void main(String[] args) {

        String db = "pack";
        String col = "col";
        String Host = "localhost";
        String Port = "27017";
        String fileName = "D:/files/sample.csv";

    String command = "C:\\Program Files\\MongoDB\\Server\\3.4\\bin\\mongoexport.exe --host " + Host + " --port " + Port + " --db " + db + " --collection " + col + " --type=csv --fields _id,email,createdAt, --out " + fileName + "";

    try {
        System.out.println(command);

        StringTokenizer st = new StringTokenizer(command);
        String[] cmdarray = new String[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++)
            cmdarray[i] = st.nextToken();

        ProcessBuilder processBuilder = new ProcessBuilder(cmdarray);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        BufferedReader processOutput = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s = "";
        while ((s = processOutput.readLine()) != null) {
            System.out.println(s);
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
Sign up to request clarification or add additional context in comments.

6 Comments

In the above program, success.readLine() is getting null, so it is entering into error.readLine() block and then it is exporting a csv file from error block of while loop. I don't know why it is exporting a csv file from error block but not from success block. Can any one help me regarding the same ...
Actually, the Java code is not writing anything specifically on the file regardless of success or failure. The command that we are executing writes data to csv file. The while loop (success or error) is just to show the message on console. If there is any error, the csv should have only header record.
Yeah, actually entire data is written into a csv file .Exported all records successfully . Everything is working fine as expected but it is exporting a csv file from error block but not from success block. This is the issue I'm facing now
Can you show what you are seeing in console i.e. Std ERROR : followed by some string ?
Had added a scrrenshot above for the stdError.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.