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

Java对MongoDB中的数据查询处理的更多相关文章

  1. 解决Spring中使用Example无法查询到Mongodb中的数据问题

    1 问题描述 在Spring Boot中使用Mongodb中的Example查询数据时查询不到,示例代码如下: ExampleMatcher matcher = ExampleMatcher.matc ...

  2. MongoDB中的数据聚合工具Aggregate和Group

    周煦辰 2016-01-16 来说说MongoDB中的数据聚合工具. Aggregate是MongoDB提供的众多工具中的比较重要的一个,类似于SQL语句中的GROUP BY.聚合工具可以让开发人员直 ...

  3. 使用highcharts显示mongodb中的数据

    1.mongodb数据表相关 # 显示数据库 show dbs # 数据库 use ceshi # 显示表 show tables # 创建集合 db.createCollection('infoB' ...

  4. java读取请求中body数据

    java读取请求中body数据 /** * 获取request中body数据 * * @author lifq * * 2017年2月24日 下午2:29:06 * @throws IOExcepti ...

  5. MongoDB中导入数据命令的使用(mongoimport)

    MongoDB中导入数据命令的使用(mongoimport) 制作人:全心全意 语法: mongoimport <options> <file> 介绍: 该命令可以将CSV,T ...

  6. 用java在客户端读取mongodb中的数据并发送至服务器

    使用Java自带的socket端口来实现,程序如下: Client.java package com.cn.gao; import java.net.*; import java.io.*; impo ...

  7. Eclipse中java向数据库中添加数据,更新数据,删除数据

    前面详细写过如何连接数据库的具体操作,下面介绍向数据库中添加数据. 注意事项:如果参考下面代码,需要 改包名,数据库名,数据库账号,密码,和数据表(数据表里面的信息) package com.ning ...

  8. 7. java操作MongoDB,采用_id查询

    转自:https://www.2cto.com/database/201704/633262.html mongodb命令行_id查询方法 直接用ObjectId() db.getCollection ...

  9. java连接redis中的数据查、增、改、删操作的方法

    package com.lml.redis; import java.util.HashMap;import java.util.Iterator;import java.util.Map;impor ...

随机推荐

  1. How do I extract a single column from a data.frame as a data.frame

    Say I have a data.frame: df <- data.frame(A=c(10,20,30),B=c(11,22,33), C=c(111,222,333))  A  B  C ...

  2. using Redis in .net core

    Using Redis Cache in .net Core Distributed Cache using Redis and ASP.NET Core ASP.NET Core Data Prot ...

  3. Tag Helpers in forms in ASP.NET Core

    Tag Helpers in ASP.NET Core Tag Helpers in forms in ASP.NET Core HTML Form element ASP.NET Core buil ...

  4. Python有趣现象(不定时更新)

    1.list中extend方法有趣现象 1.1 List+=Str 与 List.extend(Str) list1 = [11,2,45] str1 = 'Michael' list1.extend ...

  5. POJ 3693 Maximum repetition substring(连续重复子串)

    http://poj.org/problem?id=3693 题意:给定一个字符串,求重复次数最多的连续重复子串. 思路: 这道题确实是搞了很久,首先枚举连续子串的长度L,那么子串肯定包含了r[k], ...

  6. video组件的使用

    <video width="100%" height="100%" :src="downloadUrl" controls=" ...

  7. SpringMVC+fastjson项目配置

    首先这个项目得是maven项目,不是maven项目的自己引包,我就不多说了. <!-- https://mvnrepository.com/artifact/org.springframewor ...

  8. R----ggplot2包介绍学习--转载

    https://www.cnblogs.com/nxld/p/6059603.html 分析数据要做的第一件事情,就是观察它.对于每个变量,哪些值是最常见的?值域是大是小?是否有异常观测? ggplo ...

  9. 详解JS中DOM 元素的 attribute 和 property 属性

    一.'表亲戚':attribute和property 为什么称attribute和property为'表亲戚'呢?因为他们既有共同处,也有不同点. attribute 是 dom 元素在文档中作为 h ...

  10. 项目上有红色感叹号, 一般就是依赖包有问题, remove依赖,重新加载,maven的也行可认删除,自己也会得新加载

    项目上的红色叹号, 要下面提示: "Problems"  里的errors  , 看是什么错误,  一般是由于网络等原因,  依赖没有下载完整,  只有文件名字对了,  内容不全, ...