当前位置 : 主页 > 编程语言 > java >

MongoDB增删改查

来源:互联网 收集:自由互联 发布时间:2021-06-28
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.m
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
 
   mongoCollection = null;
	private MongoClient mongoClient = null;
	private MongoIterable
  
    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
   
     createDBConn() { mongoClient = new MongoClient(IPaddress, port); databaseNames = mongoClient.listDatabaseNames(); return databaseNames; } // get and set 方法 public MongoCollection
    
      getMongoCollection() { return mongoCollection; } public void setMongoCollection(MongoCollection
     
       mongoCollection) { this.mongoCollection = mongoCollection; } public MongoClient getMongoClient() { return mongoClient; } public MongoIterable
      
        getDataBaseNames() { return databaseNames; } public void printDataBaseNames() { this.getDataBaseNames().forEach(new Block
       
        (){ @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
        
          mit=this.getDataBaseNames(); final List
         
           list=new ArrayList
          
           (); mit.forEach(new Block
           
            (){@Override public void apply( String str){ list.add(str); } }); for(int i=0;i
            
              DataJsonList 要插入的数据列表 * @return 返回已插入数据的 _id主键list * */ @SuppressWarnings("static-access") public List
             
               insertMany(String DataBaseName,String CollectionName,List
              
                DataJsonList) { this.setUseDataBaase(DataBaseName); this.setUseCollection(CollectionName); List
               
                 docList=new ArrayList
                
                 (); for(int i=0;i
                 
                   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
                  
                    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
                   
                     rowList 步骤参数列表 * @return 返回插入数据的 "_id"主键 * */ public String insertTestCase(String title,String uname,int row_num,List
                    
                      rowlist) { String json="{'title':'"+title+"','uname':'"+uname+"','cdate':'"+new Date().toString()+"','row_num':"+row_num+",'rows':["; for(int i=0;i
                      
                      
                       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
                       
                        dbnames=mgu.getDataBaseNames();
		dbnames.forEach(new Block
                        
                         () { @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
                         
                           strList=new ArrayList
                          
                           (); 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
                           
                             docList=mgu.insertMany("qatest", "testlog", strList); DeleteResult delRes = null; for(int i=0;i
                            
                             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
                             
                              fiD=mgu.selectByKeyandValue("qatest","testlog","title","java_mgdb_test_javautil"); fiD.forEach(new Block
                              
                               (){ @Override public void apply(Document arg0) { // TODO Auto-generated method stub System.out.println(arg0.get("_id")); } });*/ List
                               
                                 logList=new ArrayList
                                
                                 (); 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
                                 
                                   case_rows_list=new ArrayList
                                  
                                   (); 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); } }
                                  
                                 
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       
网友评论