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. Winform异步解决窗体耗时操作(Action专门用于无返回值,Func专门用于有返回值)

    http://blog.csdn.net/config_man/article/details/25578767 #region 调用timer控件实时查询开关机时间 private void tim ...

  2. P4822 [BJWC2012]冻结

    思路 和p4568类似的分层图最短路 从上一层向下一层连边权/2的边即可 代码 #include <cstdio> #include <algorithm> #include ...

  3. The issus in Age Progression/Regression by Conditional Adversarial Autoencoder (CAAE)

    The issus in Age Progression/Regression by Conditional Adversarial Autoencoder (CAAE) Today I tried ...

  4. Docker网络配置概述

    Overview One of the reasons Docker containers and services are so powerful is that you can connect t ...

  5. layer 弹出层 回调函数调用 弹出层页面 函数

    1.项目中用到layer 弹出层,定义一个公用的窗口,问题来了窗口弹出来了,如何保存页面上的数据呢?疯狂百度之后,有了结果,赶紧记下. 2.自己定义的公共页面方法: layuiWindow: func ...

  6. Spring Security 中的加密BCryptPasswordEncoder

    // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler ...

  7. Systemd初始化进程/RHEL 6系统中System V init命令与RHEL 7系统中systemctl命令的对比

    Linux操作系统的开机过程是这样的,即从BIOS开始,然后进入Boot Loader,再加载系统内核,然后内核进行初始化,最后启动初始化进程.初始化进程作为Linux系统的第一个进程,它需要完成Li ...

  8. hibernate事务规范写法

    @Test public void testTx() { SessionFactory sessionFactory = null; Session session = null; Transacti ...

  9. Xshell5中常用linux服务器命令集合

    简易版:http://www.zhimengzhe.com/linux/84546.html 详细版:http://www.cnblogs.com/peida/tag/%E6%AF%8F%E6%97% ...

  10. 学习笔记21—PS换图片背景

    将照片红底的换成白底的. 操作步骤: 1 先上效果,照片来自网络反正不认识,法律问题找度娘 2 下面开始操作,打开图片进入通道面板,选择照片底色的那个通道,复制并调整色阶,确保黑白分明 3 回到图层面 ...