Java语言标准的数据库时MySQL,但是有些时候也会用到MongoDB,这次Boss交代处理MongoDB,所以讲代码以及思路记录下了
摸索的过程,才发现软件的适用还是很重要的啊!!!
我连接的MongoDB的数据是远程数据库,连接本地数据库的方法网上有很多:
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("106.12.34.175",27017);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("***", "***", "***".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential); //通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials); //连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("***");
MongoCollection<Document> collection = mongoDatabase.getCollection("dianping_city"); //查询过程
BasicDBObject query = new BasicDBObject();
query.put("city_num","xxx"); //查询结果
//MongoCursor<Document> cursor = collection.find(query).skip(0).limit(10).iterator();
MongoCursor<Document> cursor = collection.find(query).skip(0).iterator();
这样查询结果就有了,下面要将查询结果存储为CSV文件,我这里实现的是对查询的结果进行存储(对于多条的查询数据,也一并放入CSV文件中);存储的过程需要注意:从MongoDB返回的数据类型,多条数据类型在CSV文件中的对齐。
List<String> resultList = new LinkedList<>();
List<String> tableList = new ArrayList<>();
while (cursor.hasNext()) {
String jsonString = new String();
jsonString = cursor.next().toJson();
int length = jsonString.length();
jsonString = "[{" + jsonString.substring(jsonString.indexOf(",") + 1, length) + "]";
System.out.println(jsonString); JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
try {
if(tableList.size() == 0) {
StringBuilder stringKey = new StringBuilder();
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.compareTo("shophours") == 0){continue;}
tableList.add(key);
stringKey.append(key).append(',');
}
resultList.add(stringKey.deleteCharAt(stringKey.length()-1).toString());
}
StringBuilder stringValue = new StringBuilder();
for(String entry: tableList){
String value = new String();
if(!jsonObject.has(entry)){
value = "null";
}
else {
value = jsonObject.get(entry).toString();
}
stringValue.append(value).append(',');
}
resultList.add(stringValue.deleteCharAt(stringValue.length()-1).toString());
}
catch (JSONException e){
e.printStackTrace();
}
}
总结一下:之前没有处理过MongoDB,所以在这个small task上花了点时间,不过最后也有收获,至少MongoDB与Java相关的坑踩了一部分,为以后积累经验嘛。
整体代码:
package MongoDB; import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.*;
import java.io.*;
import java.util.*; public class outputData {
public static void main(String[] args){
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("IP",port);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("***", "***", "***".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential); //通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials); //连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("****");
MongoCollection<Document> collection = mongoDatabase.getCollection("dianping_city"); //查询过程
BasicDBObject query = new BasicDBObject();
query.put("city_num","xxx"); //查询结果
//MongoCursor<Document> cursor = collection.find(query).skip(0).limit(10).iterator();
MongoCursor<Document> cursor = collection.find(query).skip(0).iterator(); List<String> resultList = new LinkedList<>();
List<String> tableList = new ArrayList<>();
while (cursor.hasNext()) {
String jsonString = new String();
jsonString = cursor.next().toJson();
int length = jsonString.length();
jsonString = "[{" + jsonString.substring(jsonString.indexOf(",") + 1, length) + "]";
System.out.println(jsonString); JSONArray jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
try {
if(tableList.size() == 0) {
StringBuilder stringKey = new StringBuilder();
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.compareTo("shophours") == 0){continue;}
tableList.add(key);
stringKey.append(key).append(',');
}
resultList.add(stringKey.deleteCharAt(stringKey.length()-1).toString());
}
StringBuilder stringValue = new StringBuilder();
for(String entry: tableList){
String value = new String();
if(!jsonObject.has(entry)){
value = "null";
}
else {
value = jsonObject.get(entry).toString();
}
stringValue.append(value).append(',');
}
resultList.add(stringValue.deleteCharAt(stringValue.length()-1).toString());
}
catch (JSONException e){
e.printStackTrace();
}
}
cursor.close(); try {
File csv = new File("C:\\Users\\Administrator\\Desktop\\tmp2.csv");
OutputStreamWriter outStream = null;
outStream = new OutputStreamWriter(new FileOutputStream(csv), "GBK");
BufferedWriter bw = new BufferedWriter(outStream);
for(String entry : resultList){
// 添加新的数据行
bw.write(entry.toCharArray());
bw.newLine();
}
bw.close();
}
catch (FileNotFoundException e) {
// File对象的创建过程中的异常捕获
e.printStackTrace();
} catch (IOException e) {
// BufferedWriter在关闭对象捕捉异常
e.printStackTrace();
}
System.out.println("MongoDB connect successfully: "+"mongoDatabase = " + mongoDatabase.getName());
}
}
最后贴上几个为以后做准备的链接:
MongoDB安装:http://www.cnblogs.com/lzrabbit/p/3682510.html
Java下MongoDB查询:https://www.cnblogs.com/luoaz/p/4691639.html