如何使用Java将Mongodb数据读入CSV文件?

时间:2018-04-10 06:48:37

标签: java mongodb csv

请有人可以帮我解决如何将所有Mongodb数据转储到Java文件中的CSV文件吗?

我这样做了但是对于嵌套数据它不起作用。写入csv文件的目的是我需要将所有数据导出到Jtable,因为我的所有处理都是在jtable上完成的

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

    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("");
            }
        }

    }
}

0 个答案:

没有答案