远程从Mongodb 数据库导出数据为json文件

Java 连接Mongodb 数据库并且从数据库导出数据为Json文件。

需要导入三个包:

bson-3.4.3.jar

mongo-java-driver-3.4.3.jar

mongodb-driver-core-3.4.3.jar


当然版本可以改变。可以从http://mongodb.github.io/mongo-java-driver/ 这里下载

mongodb.properties:

url=localhost
port=27017



将数据导出为Json文件

public static void main(String[] args) throws IOException {
		String url = null;
		int port=27017;
		//加载
        Properties p = new Properties();
        InputStream input = MongoDbConn.class.getClassLoader().getResourceAsStream("mongodb.properties");
        try {
            p.load(input);
            url = p.getProperty("url");
            port = Integer.valueOf(p.getProperty("port"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		
        MongoClient mongoClient = new MongoClient(url, port);
		MongoDatabase md =mongoClient.getDatabase("local");
		System.out.println(md.getName());
		MongoCollection<Document> mo=md.getCollection("student");
		FindIterable<Document> f=mo.find();
		MongoCursor<Document> cm=f.iterator();
		String Json = "";
		while(cm.hasNext()){
			Json = Json + cm.next().toJson();
		}
        System.out.println(Json);
		//将Json文件 存入文件
		
		String Path = "F:/" + "1.txt";
		File file = new File(Path);
		if(file.exists()){
			System.out.println("文件存在");
		}
		else{
			file.createNewFile();
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(Json.getBytes());
			fileOutputStream.close();
			
			System.out.println("文件创建成功");
			
		}
	}


 


view pl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值