博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
自己的mongodb的CRUD封装
阅读量:6239 次
发布时间:2019-06-22

本文共 14549 字,大约阅读时间需要 48 分钟。

工具类: 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
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
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
addrs = new ArrayList
(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName, psw.toCharArray()); List
credentials = new ArrayList
(); credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(addrs,credentials); return mongoClient; } /** * 插入文档数据 * @param mongoCollection * @param params */ public void insertDoucument(final MongoCollection
mongoCollection, final Map
params){ if(null == mongoCollection) return; try { Document document = new Document(); params.keySet().stream().forEach(field -> document.append(field, params.get(field))); List
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
mongoCollection,final Map
conditionParams, final Map
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
mongoCollection,final boolean multiple, final Map
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
queryDocument(final MongoCollection
mongoCollection, final Map
conditionParams, final Integer limit, final Integer skip, final Map
sortParams, final Map
gtLtOrOtherParams,final String compareField ){ if(null == mongoCollection) return null; FindIterable
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
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
mongoCursor2 = findIterable.iterator(); while(mongoCursor2.hasNext()){ System.out.println(mongoCursor2.next()); } return findIterable; } /** * 全文查询 * @param mongoCollection * @return */ public FindIterable
queryDocument(final MongoCollection
mongoCollection ){ if(null == mongoCollection) return null; FindIterable
findIterable = mongoCollection.find(); return findIterable; } /** *带排序的查询 * @param mongoCollection * @param conditionParams * @param limit * @param skip * @param sortParams * @return */ public FindIterable
queryDocument(final MongoCollection
mongoCollection, final Map
conditionParams, final Integer limit, final Integer skip, final Map
sortParams ){ if(null == mongoCollection) return null; /** * 1. 获取迭代器FindIterable
* 2. 获取游标MongoCursor
* 3. 通过游标遍历检索出的文档集合 * */ FindIterable
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
queryDocument(final MongoCollection
mongoCollection, final Map
conditionParams ){ if(null == mongoCollection) return null; FindIterable
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
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
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
collection = mongoDBUtil.getMongoCollection(client,"whale","wb0097waterdepartmentbasic"); //1、 简单的条件查询 Map
conditionParams = Maps.newHashMap(); conditionParams.put("wbtp","003"); FindIterable
documents = mongoDBUtil.queryDocument(collection,conditionParams); mongoDBUtil.printDocuments(documents); //插入文档 for(int i=0;i<=100;i++) { Map
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
condParams = Maps.newHashMap(); condParams.put("description","database"); condParams.put("aa","bbb"); Map
updateParams = Maps.newHashMap(); updateParams.put("description","eee"); MongoDBUtil.instance().updateDocument(collection,condParams,updateParams);// //删除文档数据 Map
condParams1 = Maps.newHashMap(); condParams.put("qq",1111);// MongoDBUtil.instance().deleteDocument(collection,true,condParams1); //复杂的查询文档 Map
condParams2 = Maps.newHashMap(); condParams.put("qq","zy"); Map
sortParams = Maps.newHashMap(); sortParams.put("num",-1); sortParams.put("name",1); Map
compareParams = Maps.newHashMap(); compareParams.put("$gt",75); compareParams.put("$lt",83); FindIterable
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()); } }}

  

转载于:https://www.cnblogs.com/zyxs/p/8820483.html

你可能感兴趣的文章
线程池监控
查看>>
php源码编译常见错误解决方案
查看>>
ios 开发中UISegmentedControl 用法
查看>>
分布式网站架构后续:zookeeper技术浅析
查看>>
Redis学习(二)—— 数据类型(1)
查看>>
Darwin Streaming Server 核心代码分析
查看>>
Linux系统安装
查看>>
WordPress 后台禁用Google Open Sans字体,加速网站
查看>>
如何获取好链接??(下)
查看>>
Javascript与Ajax
查看>>
X11转发图形界面的问题处理方式
查看>>
Django 过滤器
查看>>
linux 中建立HTTPS访问
查看>>
Environment variable ORACLE_UNQNAME not defined
查看>>
Exchange各版本号收集
查看>>
NAS与SAN存储
查看>>
【Case分享】Exchange 2013EMS命令无法加载
查看>>
nrm切换npm源利器
查看>>
[C编程在Linux上]用 printf做彩色日志记录
查看>>
O365结合ADFS限制用户登录地址 (二) - 安装AAD Connect
查看>>