mongoDB工具类以及测试类【java】

java操作mongo工具类

package Utils;

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 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) {
            logger.info(NO_FOUND_MONGO_COLLECTION);
            return;
        }

        try {
            Document document = new Document();
            params.keySet().stream().forEach(field -> document.append(field, params.get(field)));

            List<Document> documents = new ArrayList<>();
            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,final boolean MultiUpdate
    ){

        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 = null;
        if (MultiUpdate){//是否批量更新
             updateResult = mongoCollection.updateMany(conditonDocument,new Document("$set",updateDocument));
        }else {
             updateResult = mongoCollection.updateOne(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 String op,final String compareField, final Map<String,Integer> gtLtOrOtherParams,
                                                final Map<String,Object> sortParams,final Integer skip,final Integer limit
                                                ){

        if(null == mongoCollection) return null;

        FindIterable<Document> findIterable = mongoCollection.find();
        Document conditionDocument = new Document();
        Document compareDocument = new Document();

        if(null != conditionParams && null != findIterable){

            conditionParams.forEach((k,v) ->{
                if (StringUtils.isNotBlank(k)) {
                    conditionDocument.append(k,v);
                }
            });

            findIterable = findIterable.filter(conditionDocument);

            MongoCursor<Document> mongoCursor = findIterable.iterator();
            while(mongoCursor.hasNext()){
                System.out.println("条件过滤  -->"+mongoCursor.next());
            }
        }

        if(null != findIterable && null != gtLtOrOtherParams){

            Document gtOrLtDoc = new Document();
            gtLtOrOtherParams.forEach((k,v) -> {
                if(StringUtils.isNotBlank(k)) gtOrLtDoc.append(k,v);
            });

            compareDocument = new Document(compareField,gtOrLtDoc);
            findIterable = findIterable.filter(new Document(compareField,compareDocument));
        }

        if (StringUtils.isNotBlank(op)){
            if ("and".equals(op)){
                findIterable = mongoCollection.find(Filters.and(conditionDocument,compareDocument));
            }else if("or".equals(op)){
                findIterable = mongoCollection.find(Filters.or(conditionDocument,compareDocument));
            }else if("not".equals(op)){//排除范围
                findIterable = mongoCollection.find(Filters.and(conditionDocument,Filters.not(compareDocument)));
            }
        }else{//默认是AND查询
            findIterable = mongoCollection.find(Filters.and(conditionDocument,compareDocument));
        }
        MongoCursor<Document> mongoCursor3 = findIterable.iterator();
        while(mongoCursor3.hasNext()){
            System.out.println(op+"过滤  -->"+mongoCursor3.next());
        }

        if(null != sortParams){
            Document sortDocument = new Document();
            sortParams.forEach((k,v) ->{
                if (StringUtils.isNotBlank(k)) {
                    sortDocument.append(k,v);
                }
            });

            findIterable = findIterable.sort(sortDocument);

            MongoCursor<Document> mongoCursor2 = findIterable.iterator();
            while(mongoCursor2.hasNext()){
                System.out.println("排序  -->"+mongoCursor2.next());
            }
        }

        if(null != findIterable && null != limit){
            findIterable = findIterable.limit(limit);
        }
        if(null != findIterable && null != skip){
            findIterable = findIterable.skip(skip);
        }

        return findIterable;
    }

    /**
     * in查询
     * @param mongoCollection
     * @return
     */
    public FindIterable<Document>  queryDocumentIn(final MongoCollection<Document> mongoCollection,String field, List<String> list
    ){

        if(null == mongoCollection) return null;
        FindIterable<Document> findIterable = mongoCollection.find(new Document(field,new Document("$in",list)));
        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
     * @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.forEach((k,v)->{
            if (StringUtils.isNotBlank(k)) {
                document.append(k,v);
            }
        });
        findIterable = findIterable.filter(document);

        return findIterable;

    }

    /**
     * 用于输出部分的列信息
     * @param documents
     */
    public static 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);

            }
        }else{
            for (Document d : documents) {
                System.out.println(d.toString());
            }
        }
    }

    /**
     * 用于输出所有的列信息
     * @param documents
     */
    public void printDocuments(FindIterable<Document> documents) {
        int num = 0;
        for (Document d : documents) {
            System.out.println("第" + (++num) + "条数据: " + d.toString());
        }
    }

}

  

mongo用到的比较常量定义

public enum MongoConst {
    GT("$gt"),
    LT("$lt"),
    GTE("$gte"),
    LTE("$lte"),
    AND("and"),
    OR("or"),
    NOT("not");
    private String compareIdentify;

    MongoConst(String compareIdentify) {
        this.compareIdentify = compareIdentify;
    }
    public String getCompareIdentify() {
        return compareIdentify;
    }
}

  

工具类的测试类

package test;

import Utils.MongoConst;
import Utils.MongoDBUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MongoTest02 {

    public static void main(String[] args) {
        MongoDBUtil mongoDBUtil = MongoDBUtil.getMongoDBUtilInstance();
        MongoClient meiyaClient = mongoDBUtil.getMongoClientByCredential("127.0.0.1",27017,"my","my","my");

        try {
            MongoCollection<Document> collection = mongoDBUtil.getMongoCollection(meiyaClient,"test","hobby");
            Map<String,Object> insert = new HashMap<>();
               //1、测试增加
           /* insert.put("name","zy");
            insert.put("age","12");
            insert.put("date","2018-04-02T09:44:02.658+0000");
            insert.put("school","厦门理工");
            mongoDBUtil.insertDoucument(collection,insert);*/
            //2、测试条件、范围、排序查询
           /* Map<String,Object> conditions = Maps.newHashMap();
            conditions.put("name","张元");
            Map<String,Integer> compares = Maps.newHashMap();
            compares.put(MongoConst.GT.getCompareIdentify(),20);
            compares.put(MongoConst.LTE.getCompareIdentify(),28);
            String opAnd = MongoConst.AND.getCompareIdentify();
            Map<String,Object> sortParams = Maps.newHashMap();
            sortParams.put("age",-1);
            FindIterable<Document> documents = mongoDBUtil.queryDocument(collection,null,opAnd,"age",compares,sortParams,null,2);
            mongoDBUtil.printDocuments(documents);*/
           //3、in查询
            /*List<String> names = Lists.newArrayList("张媛","zy","zyy");
            FindIterable<Document> documents = mongoDBUtil.queryDocumentIn(collection,"name",names);
            mongoDBUtil.printDocuments(documents);*/
            //4 批量删除
            /*Map<String,Object> conditionParams = Maps.newHashMap();
            conditionParams.put("school","厦门理工");
            long count = mongoDBUtil.deleteDocument(collection,true,conditionParams);
            System.out.println(count);*/
            //更新
            Map<String,Object> queryParams = Maps.newHashMap();
            queryParams.put("school","修改了学校");
            Map<String,Object> updateParams = Maps.newHashMap();
            updateParams.put("name","修改了名字");
            mongoDBUtil.updateDocument(collection,queryParams,updateParams,false);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }

    }
}

  

原文地址:https://www.cnblogs.com/zyxs/p/9106358.html

时间: 2024-11-09 01:02:51

mongoDB工具类以及测试类【java】的相关文章

如何在 Gradle 中运行 Groovy 的 主类以及测试类

完整的Gradle小项目:密码管理集中化 下面是配置范例 build.gradle: apply plugin: 'groovy' repositories { mavenLocal()     mavenCentral() } dependencies {     compile 'org.codehaus.groovy:groovy-all:2.3.7' compile 'org.apache.ant:ant:1.9.4'     testCompile 'junit:junit:4.11'

P1-10:编写测试类

新建测试类 编写测试类 1 package com.dszh.demo2; 2 3 import com.dszh.demo2.entity.User; 4 import com.dszh.demo2.mapper.UserMapper; 5 import org.junit.Test; 6 import org.junit.runner.RunWith; 7 import org.springframework.beans.factory.annotation.Autowired; 8 imp

JAVA单例MongoDB工具类

经常对MongoDB进行一些常用操作,为了方便起见将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以更方便的控制操作.为自己以后的积累留一个脚印. 代码如下: package utils; import java.util.ArrayList; import java.util.List; import org.apache.commons.configuration.Composite

Android实战简易教程-第五十枪(工具类的测试)

在开发中,为了提高开发效率,我们一般会自定义自己的工具类.为了保证项目的可靠性,在将工具类引入项目之前,我们一般都会对工具类进行单元测试,下面我们通过一个实例看一下如何搭建测试环境. 1.首先自定义一个工具类,这里我们自定义了一个连接图灵机器人API的网络测试类: package com.yayun.chatrobot.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.I

Java中的日历类/集合类/数学类/正则表达式/数组工具类等的常用方法与基本功能

一. Arrays 针对数组操作的工具类,提供了一些针对数组排序和二分搜索的方法.常用方法:1.public static String toString(int[] a):将int类型的数组转换成字符串.转换成字符串后输出形式: ([元素1,元素2,元素3...]),Arrays在底层重写了toString方法.2.public static void sort(int[] a):对指定的 int 型数组按数字升序进行排序.3.public static int binarySearch(in

Java基础-继承-编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。

#29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight.小车类Car是Vehicle的子类,其中包含的属性有载人数 loader.卡车类Truck是Car类的子类,其中包含的属性有载重量payload.每个 类都有构造方法和输出相关数据的方法.最后,写一个测试类来测试这些类的功 能. package hanqi; public class Vehicle { private int wheels; private int weight

java根据概率随机中奖 测试类

最近要做一个宝箱抽奖的功能 自己先联系了一下,分别用 list和set 进行存储和抽取,做了一个时间消耗的对比,感觉list应该比set读取的要快些,但是这也不一定,希望大家能够共同讨论. 废话少说上代码: package com.test.testRandom; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.u

java打开文件夹(含判断操作系统工具类和解压缩工具类)

1.Runtime.getRuntime().exec("explorer D:\\Java"); 2.java.awt.Desktop.getDesktop().open(new File("D:\\Java")); 4.java.awt.Desktop.getDesktop().browse(...) 3. try { String[] cmd = new String[5]; cmd[0] = "cmd"; cmd[1] = "/

Java测试类获取spring bean方法

Java测试类获取spring bean方法 http://blog.163.com/lizhenming_2008/blog/static/76558333201362094243911/ 1.通过spring上下文 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationcontext.xml"); DataSource ds = (DataSource) ctx.getBean("d