您的位置:首页 > 数据库 > Mongodb

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

2017-10-10 21:09 441 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: