I have used MongoDb to create some data. I want to export that data into csv file using java program.
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("");
}
}
}