我使用 MongoDb 创建一些数据。我想使用 java 程序将该数据导出到 csv 文件中。
最佳答案
您可以在文件上书写,而不是在屏幕上书写。此代码写入数据库中存在的每个集合 (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 - 使用java将MongoDB数据转换为csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31265967/