JAVA--将MongoDB数据写出到CSV

package com.ReadMongodbToCsv;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class WriteCsv {
    private static Mongo mg;
    private static DB db;
    private static BufferedWriter bw ;
    public static void main(String args[]){
        initToMongoDB();
        try {
            bw = new BufferedWriter(new FileWriter(new File("F:/vv.csv")));
            DBCollection dd = db.getCollection("zq2");
            DBCursor dc = dd.find();
            int num = 0;
            while(dc.hasNext()){
                num++;
                BasicDBObject basi = (BasicDBObject)dc.next();
                ArrayList<BasicDBObject> list = (ArrayList<BasicDBObject>)basi.get("l");
                String ss = "";
                StringBuffer sb = new StringBuffer();
                sb.append(basi.get("z") + ",");
                sb.append(basi.get("n") + ",");
                for(BasicDBObject b : list){
                    sb.append(b.get("n") + ",");
                    sb.append(b.get("t") + ",");
                }
                sb = sb.deleteCharAt(sb.length() - 1);
                bw.write(sb.toString() + "\r\n");
                if(num % 10000 == 0){
                    bw.flush();
                }
            }
            System.out.println("写入完成");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    
    public static void initToMongoDB(){
        try {
            mg = new Mongo("localhost",27017);
            db = mg.getDB("admin");
            boolean auth = db.authenticate("root", "root".toCharArray());
            if(auth){
                db = mg.getDB("test");
            }else{
                System.err.println("mongodb链接失败");
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2015-09-26 16:10  zqzdong  阅读(720)  评论(0编辑  收藏  举报