自己的mongodb的CRUD封装
工具类:
package Utils; import com.google.common.collect.Lists;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.bson.Document;
import org.bson.conversions.Bson; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map; public class MongoDBUtil {
private static MongoDBUtil mongoDBUtil; private static final String PLEASE_SEND_IP = "没有传入ip或者端口号";
private static final String PLEASE_INSTANCE_MONGOCLIENT = "请实例化MongoClient";
private static final String PLEASE_SEND_MONGO_REPOSITORY = "请指定要删除的mongo库";
private static final String DELETE_MONGO_REPOSITORY_EXCEPTION = "删除mongo库异常";
private static final String DELETE_MONGO_REPOSITORY_SUCCESS = "批量删除mongo库成功";
private static final String NOT_DELETE_MONGO_REPOSITORY = "未删除mongo库";
private static final String DELETE_MONGO_REPOSITORY = "成功删除mongo库:";
private static final String CREATE_MONGO_COLLECTION_NOTE = "请指定要创建的库";
private static final String NO_THIS_MONGO_DATABASE = "未找到指定mongo库";
private static final String CREATE_MONGO_COLLECTION_SUCCESS = "创建mongo库成功";
private static final String CREATE_MONGO_COLLECTION_EXCEPTION = "创建mongo库错误";
private static final String NOT_CREATE_MONGO_COLLECTION = "未创建mongo库collection";
private static final String CREATE_MONGO_COLLECTION_SUCH = "创建mongo库collection:";
private static final String NO_FOUND_MONGO_COLLECTION = "未找到mongo库collection";
private static final String INSERT_DOCUMEN_EXCEPTION = "插入文档失败";
private static final String INSERT_DOCUMEN_SUCCESSS = "插入文档成功"; private static final Logger logger = Logger.getLogger(MongoDBUtil.class); private MongoDBUtil(){ } private static class SingleHolder{
private static MongoDBUtil mongoDBUtil = new MongoDBUtil();
} public static MongoDBUtil instance(){ return SingleHolder.mongoDBUtil;
} public static MongoDBUtil getMongoDBUtilInstance(){
if(mongoDBUtil == null){
return new MongoDBUtil();
}
return mongoDBUtil;
} /**
* 获取mongoDB连接
* @param host
* @param port
* @return
*/
public MongoClient getMongoConnect(String host,Integer port){ if(StringUtils.isBlank(host) || null == port){
logger.error(PLEASE_SEND_IP);
return null;
} return new MongoClient(host, port);
} /**
* 批量删除mongo库
* @param mongoClient
* @param dbNames
* @return
*/
public String bulkDropDataBase(MongoClient mongoClient,String...dbNames){ if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT; if(null==dbNames || dbNames.length==0){
return PLEASE_SEND_MONGO_REPOSITORY;
}
try {
Arrays.asList(dbNames).forEach(dbName -> mongoClient.dropDatabase(dbName));
logger.info(DELETE_MONGO_REPOSITORY_SUCCESS);
}catch (Exception e){
e.printStackTrace();
logger.error(DELETE_MONGO_REPOSITORY_EXCEPTION);
}
return dbNames == null ? NOT_DELETE_MONGO_REPOSITORY:DELETE_MONGO_REPOSITORY + String.join(",",dbNames);
} /**
* 创建指定database的collection
* @param mongoClient
* @param dbName
* @param collections
* @return
*/
public String createCollections(MongoClient mongoClient,String dbName,String...collections){ if(null == mongoClient) return PLEASE_INSTANCE_MONGOCLIENT; if(null==collections || collections.length==0){
return CREATE_MONGO_COLLECTION_NOTE;
} MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
if(null == mongoDatabase) return NO_THIS_MONGO_DATABASE; try {
Arrays.asList(collections).forEach(collection -> mongoDatabase.createCollection(collection));
logger.info(CREATE_MONGO_COLLECTION_SUCCESS);
return collections == null ? NOT_CREATE_MONGO_COLLECTION:CREATE_MONGO_COLLECTION_SUCH + String.join(",",collections);
}catch (Exception e){
e.printStackTrace();
logger.error(CREATE_MONGO_COLLECTION_EXCEPTION);
} return null;
} /**
* 获取MongoCollection
* @param mongoClient
* @param dbName
* @param collection
* @return
*/
public MongoCollection<Document> getMongoCollection(MongoClient mongoClient,String dbName,String collection){ if(null == mongoClient) return null; if(StringUtils.isBlank(dbName)) return null; if(StringUtils.isBlank(collection)) return null; MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName); MongoCollection<Document> collectionDocuments = mongoDatabase.getCollection(collection); if(null == collectionDocuments) return null; return collectionDocuments;
} /**
* 获取到MongoClient
* @param ip
* @param port
* @param userName
* @param dbName
* @param psw
* @returnMongoClient
*/
public static MongoClient getMongoClientByCredential(String ip,int port,String userName,String dbName,String psw){
ServerAddress serverAddress = new ServerAddress(ip,port);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName, psw.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential); //通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs,credentials);
return mongoClient;
} /**
* 插入文档数据
* @param mongoCollection
* @param params
*/
public void insertDoucument(final MongoCollection<Document> mongoCollection, final Map<String,Object> params){
if(null == mongoCollection) return; try {
Document document = new Document();
params.keySet().stream().forEach(field -> document.append(field, params.get(field))); List<Document> documents = Lists.newArrayList();
documents.add(document);
mongoCollection.insertMany(documents);
logger.info(INSERT_DOCUMEN_SUCCESSS);
}catch (Exception e){
e.printStackTrace();
logger.error(INSERT_DOCUMEN_EXCEPTION);
}
} /**
* 更新文档
* @param mongoCollection
* @param conditionParams
* @param updateParams
*/
public void updateDocument(final MongoCollection<Document> mongoCollection,final Map<String,Object> conditionParams,
final Map<String,Object> updateParams
){ if(null == mongoCollection) return; if (null == conditionParams) return; if (null == updateParams) return; Document conditonDocument = new Document();
conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> {
conditonDocument.append(o,conditionParams.get(o));
}); Document updateDocument = new Document();
updateParams.keySet().stream().filter(p -> null != p).forEach(o -> {
updateDocument.append(o,updateParams.get(o));
});
UpdateResult updateResult = mongoCollection.updateMany(conditonDocument,new Document("$set",updateDocument)); System.out.println("修改了:"+updateResult.getModifiedCount()+" 条数据 "); } /**
*删除文档
* @param mongoCollection
* @param multiple
* @param conditionParams
* @return
*/
public long deleteDocument(final MongoCollection<Document> mongoCollection,final boolean multiple,
final Map<String,Object> conditionParams){ if(null == mongoCollection) return 0; if(null == conditionParams) return 0; Document document = new Document(); conditionParams.keySet().stream().filter(p -> null != p).forEach(o -> {
document.append(o,conditionParams.get(o));
}); if(multiple) {
return mongoCollection.deleteMany(document).getDeletedCount();
} //删除文档第一条
return mongoCollection.deleteOne(document).getDeletedCount();
} /**
* 查询文档 带范围查找、分页、排序
* @param mongoCollection
* @param conditionParams
* @param limit
* @param skip
* @param sortParams
*/
public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
final Integer limit, final Integer skip, final Map<String,Integer> sortParams,
final Map<String,Integer> gtLtOrOtherParams,final String compareField
){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(); if(null == conditionParams || null == findIterable) return findIterable; Document document = new Document();
conditionParams.keySet().stream().filter(p -> null!=p).forEach(o -> document.append(o,conditionParams.get(o))); findIterable = findIterable.filter(document); MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
if(null == findIterable || null == gtLtOrOtherParams) return findIterable; Document gtOrLtDoc = new Document();
gtLtOrOtherParams.keySet().stream().filter(p -> null!=p).forEach(o -> gtOrLtDoc.append(o,gtLtOrOtherParams.get(o))); findIterable = findIterable.filter(new Document(compareField,gtOrLtDoc)); if(null == findIterable || null == limit) return findIterable;
findIterable = findIterable.limit(limit); if(null == findIterable || null == skip) return findIterable;
findIterable = findIterable.skip(skip); if(null == sortParams) return findIterable; Document sortDocument = new Document();
sortParams.keySet().stream().filter(p -> null!=p).forEach(o -> sortDocument.append(o,sortParams.get(o))); findIterable = findIterable.filter(sortDocument);
MongoCursor<Document> mongoCursor2 = findIterable.iterator();
while(mongoCursor2.hasNext()){
System.out.println(mongoCursor2.next());
} return findIterable; } /**
* 全文查询
* @param mongoCollection
* @return
*/
public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection
){
if(null == mongoCollection) return null;
FindIterable<Document> findIterable = mongoCollection.find();
return findIterable;
} /**
*带排序的查询
* @param mongoCollection
* @param conditionParams
* @param limit
* @param skip
* @param sortParams
* @return
*/
public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams,
final Integer limit, final Integer skip, final Map<String,Integer> sortParams ){
if(null == mongoCollection) return null;
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
FindIterable<Document> findIterable = mongoCollection.find();
if(null == conditionParams || null == findIterable) return findIterable;
Document document = new Document();
conditionParams.keySet().stream().filter(p -> null!=p).forEach(o -> document.append(o,conditionParams.get(o)));
findIterable = findIterable.filter(document); if(null == findIterable || null == limit) return findIterable;
findIterable = findIterable.limit(limit); if(null == findIterable || null == skip) return findIterable;
findIterable = findIterable.skip(skip); if(null == sortParams) return findIterable; Document sortDocument = new Document();
sortParams.keySet().stream().filter(p -> null!=p).forEach(o -> sortDocument.append(o,sortParams.get(o)));
findIterable = findIterable.sort(sortDocument); return findIterable; } /**
* 查询文档 简单条件查询
* @param mongoCollection
* @param conditionParams
* @return
*/
public FindIterable<Document> queryDocument(final MongoCollection<Document> mongoCollection, final Map<String,Object> conditionParams
){ if(null == mongoCollection) return null; FindIterable<Document> findIterable = mongoCollection.find(); if(null == conditionParams || null == findIterable) return findIterable; Document document = new Document();
conditionParams.keySet().stream().filter(p -> null!=p).forEach(o -> document.append(o,conditionParams.get(o)));
findIterable = findIterable.filter(document); return findIterable; } /**
* 用于输出部分的列信息
* @param documents
*/
public void printDocuments(FindIterable<Document> documents, String[] fields) {
if (fields != null && fields.length > 0) {
int num = 0;
for (Document d : documents) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
if(fields[i].equals("catm")){ }
stringBuilder.append(fields[i] + ": "+d.getString(fields[i])+" ");
}
System.out.println("第" + (++num) + "条数据: " + stringBuilder); }
}
} /**
* 用于输出所有的列信息
* @param documents
*/
public void printDocuments(FindIterable<Document> documents) {
int num = 0;
for (Document d : documents) {
System.out.println("第" + (++num) + "条数据: " + d.toString());
}
} }
测试类:
public class Mongo {
public static void main(String[] args) {
MongoDBUtil mongoDBUtil = MongoDBUtil.getMongoDBUtilInstance();
//MongoClient client = MongoDBUtil.instance().getMongoConnect("127.0.0.1",27017); 连接本地的mongo
MongoClient client = mongoDBUtil.getMongoClientByCredential("127.0.0.1",27017,"my","my","my");
try {
MongoCollection<Document> collection = mongoDBUtil.getMongoCollection(client,"whale","wb0097waterdepartmentbasic");
//1、 简单的条件查询
Map<String,Object> conditionParams = Maps.newHashMap();
conditionParams.put("wbtp","003");
FindIterable<Document> documents = mongoDBUtil.queryDocument(collection,conditionParams);
mongoDBUtil.printDocuments(documents);
//插入文档
for(int i=0;i<=100;i++) {
Map<String, Object> params = Maps.newHashMap();
params.put("qq", "zy");
params.put("time", new Date());
params.put("name", "bb" + i);
params.put("num", i);
mongoDBUtil.insertDoucument(collection, params);
}
//更改文档
Map<String,Object> condParams = Maps.newHashMap();
condParams.put("description","database");
condParams.put("aa","bbb");
Map<String,Object> updateParams = Maps.newHashMap();
updateParams.put("description","eee");
MongoDBUtil.instance().updateDocument(collection,condParams,updateParams);
// //删除文档数据
Map<String,Object> condParams1 = Maps.newHashMap();
condParams.put("qq",1111);
//
MongoDBUtil.instance().deleteDocument(collection,true,condParams1);
//复杂的查询文档
Map<String,Object> condParams2 = Maps.newHashMap();
condParams.put("qq","zy");
Map<String,Integer> sortParams = Maps.newHashMap();
sortParams.put("num",-1);
sortParams.put("name",1);
Map<String,Integer> compareParams = Maps.newHashMap();
compareParams.put("$gt",75);
compareParams.put("$lt",83);
FindIterable<Document> documents1 = MongoDBUtil.instance().queryDocument(collection,condParams2,10,0,sortParams,compareParams,"num");
mongoDBUtil.printDocuments(documents1);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
自己的mongodb的CRUD封装的更多相关文章
- MongoDB的CRUD操作
1. 前言 在上一篇文章中,我们介绍了MongoDB.现在,我们来看下如何在MongoDB中进行常规的CRUD操作.毕竟,作为一个存储系统,它的基本功能就是对数据进行增删改查操作. MongoDB中的 ...
- MongoDB简单CRUD场景
MongoDB简单CRUD命令操作 (1)新建数据库:use 数据库名 (2)显示所有数据库:show dbs; (3)新建集合(两种方式) 隐式创建:在创建集合的同时往集合里面添加数据---db. ...
- hibernate和mybatis的之CRUD封装差别
hibernate和mybatis的之CRUD封装差别 以下讲的是基于MVC三层架构. 由于设计架构的差别,hibernate在实际编程中可以把基础的CRUD封装,比如BaseDao类.其它类只要去继 ...
- springboot连接mongodb进行CRUD
springboot连接mongodb进行CRUD的过程: 在执行以下操作前已安装了mongodb并创建了用户和数据库,使用Robo 3T可成功连接. 1.创建springboot项目,加入以下mav ...
- Java对MongoDB的CRUD
https://blog.51cto.com/aiilive/1339058 MongoDB提供的Java操作API可以说是对Mongo数据库命令的Java翻译,熟悉Mongo命令,熟悉Java操作数 ...
- 【翻译】MongoDB指南/CRUD操作(四)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...
- 【翻译】MongoDB指南/CRUD操作(三)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...
- 【翻译】MongoDB指南/CRUD操作(二)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...
- 【翻译】MongoDB指南/CRUD操作(一)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...
随机推荐
- HD ACM 水题顺序
原文传送门:http://acm.hdu.edu.cn/ 第一阶段:开始入门吧!(15天,53题) 一.输入输出练习(2天,10题) 1000.1089-1096.1001 二.简单操作:(2-4天, ...
- Convolutional Neural Network Architectures for Matching Natural Language Sentences
interaction n. 互动;一起活动;合作;互相影响 capture vt.俘获;夺取;夺得;引起(注意.想像.兴趣)n.捕获;占领;捕获物;[计算机]捕捉 hence adv. 从此;因 ...
- 使用new来分配内存
对指针的工作方式有一定的了解之后,来看看他如何实现在程序运行时分配内存.前面我们都将指针初始化为变量的地址(int * pt; pt = & a):变量是在编译时分配的有名称的内存,而指针只是 ...
- 锚点的animate使用过程中定位不准确的问题小记
源码: $('html, body, .S').animate({ scrollTop: $('.a1').offset().top - 133}, { duration: 1500, easing: ...
- p132程序代码解析
1. long before = System.currentTimeMillis(); ...... long after = System.currentTimeMillis(); 解析:该两句 ...
- 总结描述用户和组管理类命令的使用方法,系统用户相关信息,取出主机IP地址
1.列出当前系统上所有已经登录的用户的用户名,注意:同一个用户登录多次,则只显示一次即可. [root@db146 ~]# who|cut -f1 -d' ' |sort -u root 2.取出最后 ...
- Linux第六节课学习笔记
if条件测试语句可以让脚本根据实际情况自动执行相应的命令,可以分为单分支.双分支与多分支. /dev/null为无回收功能的垃圾箱. read是用来读取用户输入信息的命令,-p用来显示提示信息. fo ...
- find命令简单使用
find命令是Linux系统查找文件的命令,能帮助用户在使用.管理Linux的日常事务时方便的查找出用户所需要的文件,find命令基本格式是:find [路径] [选项] [操作]. 列举一下find ...
- java8_api_正则表达式
正则表达式 什么是正则表达式 使用String类中的replaceAll方法 使用Pattern类编译正则表达式 使用Matcher类匹配正则表达式 什么是正则表达式 ...
- ffmpeg-4.1.1-win64-dev在vs2017的搭建
没得话讲,先在官网下载对应的源码,下载dev/文件夹下的源码和静态链接库 ,下载/shared文件夹下的动态链接库 官网地址:https://ffmpeg.zeranoe.com/builds/wi ...