MongoDB增删改查

java

浏览数:217

2019-1-7

AD:资源代下载服务

片段 1片段 2片段 3片段 4


MongoDB增删改查

package com.qatest.mongo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.qatest.dao.createInfo;public class mongoUtil {
    private int port = 27017;
    private String IPaddress = "127.0.0.1";
    private MongoCollection<Document> mongoCollection = null;
    private MongoClient mongoClient = null;
    private MongoIterable<String> databaseNames = null;
    private MongoDatabase mongoDataBase=null;
    
    /**
    *无参构造函数
    *@author javaboy
    *@Time 2017-11-08 20:05:00
    *@return 构造完成直接获得 mongoUtil 对象用于数据库相关操作
    */
    public mongoUtil() {
        this.createDBConn();
    }
    /**
    *有参构造函数
    *@author javaboy
    *@Time 2017-11-08 20:05:00
    *@param IPaddress 指定需要连接的MongoDB地址  (String)
    *@param port      指定需要链接的MongoDB端口 (Int)
    *@return 构造完成直接获得 mongoUtil 对象用于数据库相关操作
    */
    public mongoUtil(String IPaddress, int port) {
        this.port = port;
        this.IPaddress = IPaddress;
        this.createDBConn();
    }
    //私有的 用于本类内创建与数据库的连接
    private MongoIterable<String> createDBConn() {
        mongoClient = new MongoClient(IPaddress, port);
        databaseNames = mongoClient.listDatabaseNames();
        return databaseNames;
    }
    
    // get and set 方法
    public MongoCollection<Document> getMongoCollection() {
        return mongoCollection;
    }

    public void setMongoCollection(MongoCollection<Document> mongoCollection) {
        this.mongoCollection = mongoCollection;
    }

    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public MongoIterable<String> getDataBaseNames() {
        return databaseNames;
    }
    
    public void printDataBaseNames()
    {
           this.getDataBaseNames().forEach(new Block<String>(){
            @Override public void apply(final String str){
                System.out.println("当前server数据库名称:"+str);
            }
        });
    }

    public MongoDatabase getMongoDataBase() {
        return mongoDataBase;
    }

    //退出数据库
    public boolean closeDB()
    {
        if(mongoClient != null)
        {
            mongoClient.close();
            return true;
        }else{
            return true;
        }
    }
    
    //判断数据库是否已经连接返回校验过的mongoClient对象实例(私有方法)
    private MongoClient getExistenceMongoClient() throws Exception
    {
        if(mongoClient!=null)
        {
            return mongoClient;
        }else
        {
            throw new  Exception("链接异常:没有找到可用的mongodb连接");
    
        }
    }
    //验证输入的数据库是否存在 返回boolean类型(私有方法)
    public boolean checkDBExistence( String dataBaseName)
    {
         
        MongoIterable<String> mit=this.getDataBaseNames();
        final List<String> list=new ArrayList<String>();
        mit.forEach(new Block<String>(){@Override public void apply( String str){
            list.add(str);
            } });
        for(int i=0;i<list.size();i++)
        {
            if(dataBaseName.equals(list.get(i)))
            {
                return true;
            }
        }
        return false;
        
    }
    
    
    //进入数据库
    public void setUseDataBaase(String dataBaseName)
    {
        try {
        if(!dataBaseName.equals(null)&&!" ".equals(dataBaseName))
        {
            
                 mongoDataBase=this.getExistenceMongoClient().getDatabase(dataBaseName);
            
        }else{
            System.out.println("没有找到名称为"+dataBaseName+"的数据库,默认已跳转test库");
            mongoDataBase=this.getExistenceMongoClient().getDatabase("test");
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    //进入集合
    public void setUseCollection(String collectionName)
    {
        if(!mongoDataBase.equals(null)&&this.checkDBExistence(this.mongoDataBase.getName()))
        {
             mongoCollection=mongoDataBase.getCollection(collectionName);
        }
    }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~基本操作~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++增++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    /**
     * 向指定数据库中指定集合插入一条数据
     * @author javaboy
     * @param String DataBaseName    要插入的数据库
     * @param String CollectionName  要插入的集合
     * @param String DataJson          数据体以Json格式插入
     * @return 返回已插入数据的 Document对象
     * */
    
    @SuppressWarnings("static-access")
    public Document insertOne(String DataBaseName,String CollectionName,String DataJson)
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        Document doc= new Document().parse(DataJson);
        this.mongoCollection.insertOne(doc);
        return doc;
        
        
    }

    /**
     * 向指定数据库中指定集合插入多条数据
     * @author javaboy
     * @param String DataBaseName    要插入的数据库
     * @param String CollectionName  要插入的集合
     * @param List<String> DataJsonList     要插入的数据列表
     * @return 返回已插入数据的 _id主键list
     * */
    @SuppressWarnings("static-access")
    public List<Document> insertMany(String DataBaseName,String CollectionName,List<String> DataJsonList)
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        List<Document> docList=new ArrayList<Document>();
        for(int i=0;i<DataJsonList.size();i++)
        {
            
            Document doc=new Document().parse(DataJsonList.get(i));
            docList.add(doc);
        }
        this.mongoCollection.insertMany(docList);
        return docList;
    }
    
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++删++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    /**
     * 根据_id删除一条数据
     * @author javaboy
     * @param String DataBaseName    指定的数据库
     * @param String CollectionName  指定的集合
     * @param String _id       指定条件
     * @return 返回影响的数据结果
     * */
    
    public DeleteResult deleteDataById(String DataBaseName,String CollectionName,String _id )
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        return this.mongoCollection.deleteOne(Filters.eq("_id", new ObjectId(_id)));
    }
    
    /**
     * 根据任意字段删除一条数据
     * @author javaboy
     * @param String DataBaseName    指定的数据库
     * @param String CollectionName  指定的集合
     * @param String str      指定条件
     * @return 返回影响的数据结果
     * */
    
    public DeleteResult deleteOneDataByKeyandValue(String DataBaseName,String CollectionName,String Key,String Value )
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        return this.mongoCollection.deleteOne(Filters.eq(Key, Value));
    }
    
    /**
     * 根据任意字段删除多条数据
     * @author javaboy
     * @param String DataBaseName    指定的数据库
     * @param String CollectionName  指定的集合
     * @param String str      指定条件
     * @return 返回影响的数据结果
     * */
    public DeleteResult deleteManyDataByKeyandValue(String DataBaseName,String CollectionName,String Key,String Value )
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        return this.mongoCollection.deleteMany(Filters.eq(Key, Value));
    }
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++查++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    /**
     * 通过_id查询一条数据
     * @author javaboy
     * @param String DataBaseName    指定的数据库
     * @param String CollectionName  指定的集合
     * @param String select_Id       _id
     * @return 返回查询结果集
     * */
    public FindIterable<Document> selectById(String DataBaseName,String CollectionName,String select_Id)
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        return this.mongoCollection.find(Filters.eq("_id", new ObjectId(select_Id)));
    }
    
    /**
     * 通过_id查询一条数据
     * @author javaboy
     * @param String DataBaseName    指定的数据库
     * @param String CollectionName  指定的集合
     * @param String select_Id       _id
     * @return 返回查询结果集
     * */
    public FindIterable<Document> selectByKeyandValue(String DataBaseName,String CollectionName,String Key,String Value)
    {
        this.setUseDataBaase(DataBaseName);
        this.setUseCollection(CollectionName);
        return this.mongoCollection.find(Filters.eq(Key, Value));
    }

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++改+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
 * 通过_id来修改一条数据 ,使用时请学习 MongoDB 修改器的用法
 * @author javaboy
 * @param String DataBaseName    指定的数据库
 * @param String CollectionName  指定的集合
 * @param String select_Id       _id
 * @return 返回影响的数据结果集
 * */
     public UpdateResult updateById(String DataBaseName,String CollectionName,String select_Id,String upJson)
     {
         this.setUseDataBaase(DataBaseName);
         this.setUseCollection(CollectionName);
         return this.mongoCollection.updateOne(Filters.eq("_id", new ObjectId(select_Id)), Document.parse(upJson));
     } 
/**
 * 通过Key and Value来定位一条或多条数据 并修改指定字段,使用时请学习 MongoDB 修改器的用法
 * @author javaboy
 * @param String DataBaseName    指定的数据库
 * @param String CollectionName  指定的集合
 * @param String upKey           条件键
 * @param String upValue         条件值
 * @param String upJson          修改的字段
 * @return 返回影响的数据结果集 
 * */
     public UpdateResult updateByKeyandValue(String DataBaseName,String CollectionName,String upKey,String upValue,String upJson)
     {
         this.setUseDataBaase(DataBaseName);
         this.setUseCollection(CollectionName);
         return this.mongoCollection.updateOne(Filters.eq(upKey, upValue), Document.parse(upJson));
     }
     
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++针对数据集的操作++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     /**
      * 插入一条日志 json格式{'case_id':xxxx,'type':xxxx,'date':new Date().toString(),'log':xxxxx}
      * @author javaboy      
      * @param String case_id 与任务关联的建,做联合查询时有用
      * @param String type    日志类型例如: error、info、warning
      * @param String log     日志内容
      * */
     public void insertTestLog(String case_id,String type,String log)
     {
         String json="{'case_id':ObjectId('"+case_id+"'),'type':'"+type+"','date':'"+new Date().toString()+"','log':'"+log+"'}";
         this.getMongoCollection().insertOne(Document.parse(json));
     }
     /**
      * 插入一条日志 json格式{
      *                      'title':xxxx,
      *                      'uname':xxxx,
      *                      'cdate':new Date().toString(),
      *                      'row_num':0,
      *                      'rows':[
      *                                 {
      *                                     'number':"+this.number+",
      *                                     'kj_var':'"+this.kj_var+"',
      *                                     'dz_var':'"+this.dz_var+"',
      *                                     'cs_var':'"+this.cs_var+"',
      *                                     'bz_var':'"+this.bz_var+"'
      *                                 }
      *                                 {......}
      *                                 {......}
      *                                 {}......
      *                             ]
      *                       }
      * @author javaboy      
      * @param String title   任务标题
      * @param String uname   任务创建人    
      * @param int    row_num 任务行数
      * @param Llist<createInfo> rowList 步骤参数列表
      * @return 返回插入数据的 "_id"主键
      * */
     public String insertTestCase(String title,String uname,int row_num,List<createInfo> rowlist)
     {
         String json="{'title':'"+title+"','uname':'"+uname+"','cdate':'"+new Date().toString()+"','row_num':"+row_num+",'rows':[";
         for(int i=0;i<rowlist.size();i++)
         {
             if(i==0)
             {
                 json+=rowlist.get(i).toJsonStr();
             }else
             {
                 json+=","+rowlist.get(i).toJsonStr();
             }
             
         }
         json+="]}";
         @SuppressWarnings("static-access")
         Document doc=new Document().parse(json);
         this.getMongoCollection().insertOne(doc);
         return doc.get("_id").toString();
     }
     /**
      * 插入一个任务的结果集
      * {
      * "case_id":"",
      * "zt_var":false,
      * "jg_var":false,
      * "cs_var":""
      * }
      * @param String case_id 任务id
      * @param boolean zt_var 状态
      * @param boolean jg_var 结果
      * @param String cs_var  参数
      * @return "_id"主键
      * */
     public String insterCaseResult(String case_id,boolean zt_var,boolean jg_var,String cs_var)
     {
         String json="{'case_id':'"+case_id+"','zt_var':"+zt_var+",'jg_var':"+jg_var+",'cs_var':'"+cs_var+"'}";
         @SuppressWarnings("static-access")
        Document jsonDoc=new Document().parse(json);
         this.getMongoCollection().insertOne(jsonDoc);
         return jsonDoc.get("_id").toString();
        
     }
}


createInfo类

package com.qatest.dao;

public class createInfo {
    private String kj_var;
    private String dz_var;
    private String cs_var;
    private String bz_var;
    private int number;
    private String result_id;
    
    

    //构造函数
    public createInfo()
    {
        this.setNumber(0);
        this.setKj_var(null);
        this.setBz_var(null);
        this.setCs_var(null);
        this.setDz_var(null);
        this.setResult_id(null);
    }
    
    public createInfo(int number,String kj_var,String bz_var,String cs_var,String dz_var,String result_id)
    {
        this.setNumber(number);
        this.setKj_var(kj_var);
        this.setBz_var(bz_var);
        this.setCs_var(cs_var);
        this.setDz_var(dz_var);
        this.setResult_id(result_id);
    }
    
    //get and set
    public String getKj_var() {
        return kj_var;
    }
    public void setKj_var(String kj_var) {
        this.kj_var = kj_var;
    }
    public String getDz_var() {
        return dz_var;
    }
    public void setDz_var(String dz_var) {
        this.dz_var = dz_var;
    }
    public String getCs_var() {
        return cs_var;
    }
    public void setCs_var(String cs_var) {
        this.cs_var = cs_var;
    }
    public String getBz_var() {
        return bz_var;
    }
    public void setBz_var(String bz_var) {
        this.bz_var = bz_var;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public String getResult_id() {
        return result_id;
    }

    public void setResult_id(String result_id) {
        this.result_id = result_id;
    }
    //toString 
    //toJsonStr
    public String toJsonStr()
    {
        return new String("{'number':"+this.number+",'kj_var':'"+this.kj_var+"','dz_var':'"+this.dz_var+"','cs_var':'"+this.cs_var+"','bz_var':'"+this.bz_var+"','result_id':'"+this.result_id+"'}");
    }
    
    
}


logoUtil类

package com.qatest.dao;

import com.qatest.mongo.mongoUtil;

public class logUtil {
    private String case_id;
    private mongoUtil mgu;
    
//有参构造函数
public logUtil(mongoUtil mgu,String case_id,String type,String log)
{
    mgu.insertTestLog(case_id, type, log);
    this.case_id=case_id;
    this.mgu=mgu;
}
//写入一条日志
public void writeLog(String type,String log)
{
    this.mgu.insertTestLog(case_id, type, log);
}

}


测试代码

package com.qatest.mongo.test;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Test;

import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import com.qatest.dao.createInfo;
import com.qatest.dao.logUtil;
import com.qatest.mongo.mongoUtil;public class testDBUtil {

    //@BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    //@AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    //@Before
    public void setUp() throws Exception {
    }

    //@After
    public void tearDown() throws Exception {
    }

    //@Test
    public void testDBUtil()  {
        mongoUtil mgu=new mongoUtil("172.17.104.127",27017);
        /*MongoIterable<String>dbnames=mgu.getDataBaseNames();
        dbnames.forEach(new Block<String>() { 
              @Override public void apply(final String str) { 
                    System.out.println(str); }
            });*/

        mgu.setUseDataBaase("testcase");
        mgu.printDataBaseNames();
        //System.out.println(mgu.checkDBExistence("local"));
        mgu.setUseCollection("testcase");
        /*Date now=new Date();
        
        String DateJsonString="{'date':'"+now.toString()+"','title':'java_mgdb_test_javautil','type':'info','info':[{'date':'10:21','log':'这是一条测试数据'},{'date':'10:22','log':'这是一条测试数据'}]}";;
        Document doc=mgu.insertOne("qatest", "testlog", DateJsonString);
        System.out.println(doc.get("_id"));*/
        /*
        List<String> strList=new ArrayList<String>();
        for(int i=0;i<5;i++)
        {
            Date now=new Date();
            String DataJsonString="{'date':'"+now.toString()+"','title':'java_mgdb_test_javautil"+i+"','type':'info','info':[{'date':'10:21','log':'这是一条测试数据'},{'date':'10:22','log':'这是一条测试数据'}]}";
            strList.add(DataJsonString);
        }
        List<Document> docList=mgu.insertMany("qatest", "testlog", strList);
        DeleteResult delRes = null;
        for(int i=0;i<docList.size();i++)
        {
            System.out.println("批量插入的数据_id:"+docList.get(i).get("_id"));
             delRes=mgu.deleteDataById("qatest", "testlog",docList.get(i).get("_id").toString());
             System.out.println("删除批量数据"+delRes.getDeletedCount());
        }
        
        DeleteResult delRes=mgu.deleteManyDataByKeyandValue("qatest", "testlog", "title", "java_mgdb_test_javautil");
        System.out.println(delRes.getDeletedCount());
        
        FindIterable<Document>fi=mgu.selectById("qatest", "testlog", "5a056c772b99780fec66cad1");
        System.out.println(fi.first().get("_id"));
        //UpdateResult ur= mgu.updateById("qatest", "testlog", "5a056c772b99780fec66cad1", "{'$push':{'info':{'date':'2017/11/10 20:28','log':'这条数据是2017/11/10 20:28增加的'}}}");
        UpdateResult ur1= mgu.updateById("qatest", "testlog", "5a056c772b99780fec66cad1", "{'$set':{'type':'Error'}}");
        System.out.println(ur1.getMatchedCount());*/
        /*FindIterable<Document>fiD=mgu.selectByKeyandValue("qatest","testlog","title","java_mgdb_test_javautil");
        fiD.forEach(new Block<Document>(){
            @Override
            public void apply(Document arg0) {
                // TODO Auto-generated method stub
                System.out.println(arg0.get("_id"));
            }
        });*/
        List<createInfo> logList=new ArrayList<createInfo>();
        createInfo li=new createInfo(0,"aaa","aaa","aaa","aaa","aaa");
        createInfo li1=new createInfo(1,"bbb","bbb","bbb","bbb","aaa");
        createInfo li2=new createInfo(2,"ccc","ccc","ccc","ccc","aaa");
        createInfo li3=new createInfo(3,"ddd","ddd","ddd","ddd","aaa");
        logList.add(li);
        logList.add(li1);
        logList.add(li2);
        logList.add(li3);
        String objid=mgu.insertTestCase("test", "javaboy",4,logList);
        System.out.println(objid);
        mgu.setUseCollection("testlog");
        logUtil lu=new logUtil(mgu,objid,"info","写入第一条日志");
        lu.writeLog("error", "这是一条错误日志");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lu.writeLog("error","这是2条错误日志");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lu.writeLog("error","这是3条错误日志");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        lu.writeLog("info","1条正常的日志");
        mgu.setUseCollection("caseresult");
        System.out.println(mgu.insterCaseResult("", false, false, ""));
    }
     
    @Test
    public void testCreateCase()
    {
        List<createInfo> case_rows_list=new ArrayList<createInfo>();
        case_rows_list.add(new createInfo(0,"appium","123","12928657|111|true|20|","用户举报","null"));
        case_rows_list.add(new createInfo(1,"selenuim","123","12928657|111|true|20|","用户举报","null"));
        mongoUtil mgu=new mongoUtil("172.17.104.127",27017);
        mgu.setUseDataBaase("testcase");
        mgu.setUseCollection("testcase");
        String case_id=mgu.insertTestCase("测试流程","javaboy",2, case_rows_list);
        mgu.setUseCollection("caseresult");
        String result_id0=mgu.insterCaseResult(case_id, false, false, "null");
        String result_id1=mgu.insterCaseResult(case_id, false, false, "null");
        UpdateResult ur1=mgu.getMongoDataBase().getCollection("testcase").updateOne(Filters.eq("_id",new ObjectId(case_id)),Document.parse("{'$set':{'rows.0.result_id':'"+result_id0+"'}}"));
        mgu.getMongoDataBase().getCollection("testcase").updateOne(Filters.eq("_id",new ObjectId(case_id)),Document.parse("{'$set':{'rows.1.result_id':'"+result_id1+"'}}"));
        mgu.setUseCollection("testlog");
        logUtil logutil=new logUtil(mgu,case_id,"info","测试流程--javaboy"+case_id+"已经创建成功");
        System.out.println(ur1);
    }
}