1

I have used MongoDb to create some data. I want to export that data into csv file using java program.

2
  • Why do you need only java program? If data is converted from MongoDB to csv, your goal should have been achieved. Please check below question : stackoverflow.com/questions/19862137/… Commented Jul 7, 2015 at 10:37
  • I have tried with that. I need it in java program Commented Jul 7, 2015 at 10:55

1 Answer 1

1

Instead to write on screen you can write on a file. This code writes every collection present in your db (Your_Db_Name).

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("YOUR_DB_NAME");

ListCollectionsIterable collections = db.listCollections();

MongoCursor collectionsCursor = collections.iterator();

while (collectionsCursor.hasNext()) {
    Document collectionDocument = (Document) collectionsCursor.next();

    String name = collectionDocument.getString("name");
    if (!name.equalsIgnoreCase("system.indexes")) {
        MongoCollection collectionTemp = db.getCollection(name);

        boolean collectionFirst = true;
        MongoCursor < Document > cursorDoc = collectionTemp.find().iterator();
        while (cursorDoc.hasNext()) {

            Document collectionElement = cursorDoc.next();
            boolean first = true;
            Set < String > keySet = collectionElement.keySet();
            if (collectionFirst) {
                for (String key: keySet)
                if (first) {
                    System.out.print(key);
                    first = !first;
                } else System.out.print("," + key);

                collectionFirst = !collectionFirst;
                System.out.println("");
            }
            first = true;
            for (String key: keySet)
            if (first) {
                System.out.print(collectionElement.get(key));
                first = !first;
            } else System.out.print("," + collectionElement.get(key));

            System.out.println("");
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.