使用java将MongoDB数据转换为csv

时间:2015-07-07 10:24:50

标签: java mongodb csv

我使用MongoDb创建了一些数据。我想使用java程序将该数据导出到csv文件中。

1 个答案:

答案 0 :(得分:1)

而是在屏幕上书写,您可以在文件上书写。此代码会写入数据库中存在的每个集合( 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("");
        }
    }
}