使用Java将MongoDB数据转换为CSV [英] Convert MongoDB data into csv using java
本文介绍了使用Java将MongoDB数据转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用MongoDb创建了一些数据.我想使用Java程序将该数据导出到csv文件中.
I have used MongoDb to create some data. I want to export that data into csv file using java program.
推荐答案
您可以在文件上书写,而不是在屏幕上书写.这段代码会写出您的数据库( Your_Db_Name )中存在的每个集合.
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("");
}
}
}
这篇关于使用Java将MongoDB数据转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文