Convert MongoDB data into csv using java

后端 未结 1 1184
醉酒成梦
醉酒成梦 2021-01-27 15:42

I have used MongoDb to create some data. I want to export that data into csv file using java program.

相关标签:
1条回答
  • 2021-01-27 16:07

    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("");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题