mongoTemplate的DBObject对象查询

准备工作

  • 用idea构建Springboot构建JAVA项目,用的1.5.19.RELEASE版本,选择mongodb数据库,这个版本带的是mongodb-driver-3.4.3.jar
  • 构建数据结构 例如:文档中存的是每个人简历
	 {
		 "_id" : 8,
		 "name" : "小灰灰",
		 "age" : 26,
		 "sex" : "男",
		 "university" : { //毕业的学校
			 "name" : "北京大学",
			 "address" : "北京"
		 },
		 "workExperience" : [{ //工作经历
			 "startDate" : "2010-10-10",
			 "endDate" : "2013-06-06",
			 "address" : "深圳",
			 "name" : "腾讯"
		 }]
	 }

新建DBObjectQueryDao类来访问mongodb数据库

DBObjectQueryDao中的公用方法用的fastjson格式化结果方便查看

	/**
	 * 为了结果好看格式化输出Json
	 * 查看查询条件
	 * 结果条数
	 * @param result
	 */
	public void parseJson(DBCursor result){
		System.out.println(JSON.toJSONString(result,true));
		System.out.println(result.getQuery());
		System.out.println(result.size());
	}

  • dao层代码
    /**
     * 保存数据 save 或者 insert
     * insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,
     * 可以一次插入多条数据
     × save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。只能save一条数据
     * @param dbObject
     */
    public void saveOne(DBObject dbObject){
        mongoTemplate.getCollection(CollectionName).save(dbObject);
    }
    public void insertOne(DBObject dbObject){
        mongoTemplate.getCollection(CollectionName).insert(dbObject);
    }
    public void insertMany(List<DBObject> dbObject){
        mongoTemplate.getCollection(CollectionName).insert(dbObject);
    }

测试代码(调用dao层)

	/**
	 * 插入一条数据
	 * 	 
	 {
		 "_id" : 8,
		 "name" : "小灰灰",
		 "age" : 26,
		 "sex" : "男",
		 "university" : {
			 "name" : "北京大学",
			 "address" : "北京"
		 },
		 "workExperience" : [{
			 "startDate" : "2010-10-10",
			 "endDate" : "2013-06-06",
			 "address" : "深圳",
			 "name" : "腾讯"
		 }]
	 }
	 */
	@Test
	public void insertOneListDocument(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",8);
		dbObject.put("name","小灰灰");
		dbObject.put("age",26);
		dbObject.put("sex","男");

		DBObject dbObject1 = new BasicDBObject();
		dbObject1.put("name","北京大学");
		dbObject1.put("address","北京");

		dbObject.put("university",dbObject1);

		DBObject dbObject2 = new BasicDBObject();
		dbObject2.put("startDate","2010-10-10");
		dbObject2.put("endDate","2013-06-06");
		dbObject2.put("address","深圳");
		dbObject2.put("name","腾讯");

		List<DBObject> dbObjectList = new ArrayList<>();//对象数组
		dbObjectList.add(dbObject2);

		dbObject.put("workExperience",dbObjectList);

		dbObjectQueryDao.insertOne(dbObject);
		//直接看下结果
		System.out.println(dbObjectQueryDao.findOne(new BasicDBObject().append("_id",8)));
	}
		/**
	 * 插入多条数据
	 */
	@Test
	public void insertData(){
		List<DBObject> list =new ArrayList<>();
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",9);
		dbObject.put("name","小雪");
		dbObject.put("age",22);
		dbObject.put("sex","女");
		DBObject dbObject1 = new BasicDBObject();
		dbObject1.put("_id",10);
		dbObject1.put("name","小燕子");
		dbObject1.put("age",23);
		dbObject1.put("sex","女");
		list.add(dbObject);
		list.add(dbObject1);
		dbObjectQueryDao.insertMany(list);
	}

  • dao层代码
    /**
     * 根据条件查询所有符合条件的结果
     * @param dbObject
     * @return
     */
//    public DBCursor find(DBObject dbObject){
//        return mongoTemplate.getCollection(CollectionName).find(dbObject);
//    }

    public DBCursor find(DBObject dbObject){
        return this.find(dbObject,null);
    }

    /**
     * 根据条件查询所有符合条件的结果,并指定返回字段
     * @param query
     * @param projection
     * @return
     */
    public DBCursor find(DBObject query, DBObject projection){
        return mongoTemplate.getCollection(CollectionName).find(query,projection);
    }
    /**
     * 分页查询
     * @param query
     * @param skip
     * @param limit
     * @return
     */
    public DBCursor findPage(DBObject query,int skip,int limit){
        return mongoTemplate.getCollection(CollectionName).find(query).skip(skip).limit(limit);
    }
  /**
     * 查询条数
     * @param query
     * @return
     */
    public Long count(DBObject query){
        return mongoTemplate.getCollection(CollectionName).count(query);
    }

测试代码

	/**
	 * 查询_id:1的信息
	 */
	@Test
	public void findOneTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id","1");
		DBObject result=dbObjectQueryDao.findOne(dbObject);
		System.out.println(result.toString());
	}

	/**
	 * 查询性别为 女 的所有人的简历
 	 */
	@Test
	public void findMultiTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("sex","女");
		DBCursor result=dbObjectQueryDao.find(dbObject);
		this.parseJson(result);//结果
	}

	/**
	 * in 查询 $in
	 * 反向的用 $nin
	 */
	@Test
	public void findMultiWithInTest(){
		DBObject dbObject = new BasicDBObject();//查询条件
		dbObject.put("_id",new BasicDBObject().append("$in", Arrays.asList(8,9)));
		DBObject fieldObject = new BasicDBObject();//指定返回字段
		fieldObject.put("_id",true);
		fieldObject.put("name",true);
		DBCursor result = dbObjectQueryDao.find(dbObject,fieldObject);
		this.parseJson(result);//结果
	}

	/**
	 * or 查询
	 * 取的是并集
	 */
	@Test
	public void findMultiWithOrTest(){
		DBObject dbObject1 = new BasicDBObject();//条件1
		dbObject1.put("sex" , "女");
		DBObject dbObject2 = new BasicDBObject();//条件2
		dbObject2.put("age" , 22);
		DBObject dbObject = new BasicDBObject();
		dbObject.put("$or",Arrays.asList(dbObject1,dbObject2));//组合
		DBCursor result = dbObjectQueryDao.find(dbObject);
		this.parseJson(result);
	}

	/**
	 * and 查询
	 * 取的是交集
	 * 通常我们写在一块,即:
	 * DBObject dbObject = new BasicDBObject();
	 * dbObject.put("sex" , "女");
	 * dbObject.put("age" , "22");
	 * 这里这是为了说明and查询,复杂的查询可能要用到
	 */
	@Test
	public void findMultiWithAndTest(){
		DBObject dbObject1 = new BasicDBObject();//条件1
		dbObject1.put("sex" , "女");
		DBObject dbObject2 = new BasicDBObject();//条件3
		dbObject2.put("age" , 22);
		DBObject dbObject = new BasicDBObject();
		BasicDBList basicDBList=new BasicDBList();//用自带的构建List
		basicDBList.add(dbObject1);
		basicDBList.add(dbObject2);
		//basicDBList等于Arrays.asList(dbObject1,dbObject2) 我们自己构建List;
		dbObject.put("$and",basicDBList);//组合
		DBCursor result = dbObjectQueryDao.find(dbObject);
		this.parseJson(result);
	}

	/**
	 * $gt:大于
	 * $lt:小于
	 * $gte:大于等于
	 * $lte:小于等于
	 * $ne:不等于
	 */
	@Test
	public void findMultiWithGtTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("age" , new BasicDBObject().append("$gt",22));
		//dbObject.put("age" , new BasicDBObject().append("$gt",22).append("$lt",24));
		DBCursor result = dbObjectQueryDao.find(dbObject);
		this.parseJson(result);
	}

	/**
	 * 模糊查询
	 * mongodb用的是正则表达式来进行模糊查询的
	 *
	 *  Spring中不区分大小写的模糊查询:
	 * //完全匹配
	 * Pattern pattern = Pattern.compile("^小$", Pattern.CASE_INSENSITIVE);
	 * //右匹配
	 * Pattern pattern = Pattern.compile("^.*小$", Pattern.CASE_INSENSITIVE);
	 * //左匹配
	 * Pattern pattern = Pattern.compile("^小.*$", Pattern.CASE_INSENSITIVE);
	 * //模糊匹配
	 * Pattern pattern = Pattern.compile("^.*小.*$", Pattern.CASE_INSENSITIVE);
	 */
	@Test
	public void findMultiWithPatternTest(){
		String name ="小";
		Pattern pattern=Pattern.compile("^.*"+name+".*$", Pattern.CASE_INSENSITIVE);
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name" , pattern);
		DBCursor result = dbObjectQueryDao.find(dbObject);
		this.parseJson(result);
	}

	/**
	 * 分页查询
	 */
	@Test
	public void findMultiWithPageTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("sex","男");
		DBCursor result = dbObjectQueryDao.findPage(dbObject,0,10);// 第一页10条
		this.parseJson(result);
	}
	/**
	 * 条数
	 */
	@Test
	public void countTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("sex","女");
		Long result = dbObjectQueryDao.count(dbObject);
		System.out.println(result);
	}

  • dao层代码
    /**
     * 删除
     * @param query
     */
    public void remove(DBObject query){
        mongoTemplate.getCollection(CollectionName).remove(query);
    }

测试代码

	/**
	 * 删除
	 *
	 * 删除多条的话用$in 放在list里面
	 * dbObject.put("_id",new BasicDBobject("$in",Arrays.asList(1,2)));
	 */
	@Test
	public void removeTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("name","test");
		dbObjectQueryDao.remove(dbObject);
	}
  • 修改
    dao层代码
    /**
     * 修改
     * @param query
     * @param update
     * update(query,update) 默认 修改一条数据
     * update(query,update,true,false) 修改一条数据 如果不存在则插入
     * update(query,update,false,true) 修改多条数据数据
     */
    public void update(DBObject query,DBObject update){
        mongoTemplate.getCollection(CollectionName).update(query,update);
    }

测试代码

	/**
	 * 修改一条数据
	 */
	@Test
	public void updateOneTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",1);
		DBObject updateObject = new BasicDBObject();
		updateObject.put("name","test");
		DBObject setObject = new BasicDBObject();
		setObject.put("$set",updateObject);
		dbObjectQueryDao.update(dbObject,setObject);
	}

	/**
	 * 修改一条数据 修改文档中的对象
	 */
	@Test
	public void updateOneInObjectTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",2);
		DBObject updateObject = new BasicDBObject();
		updateObject.put("name","北京大学");
		updateObject.put("address","北京");
		DBObject setObject = new BasicDBObject();
		setObject.put("$set",new BasicDBObject().append("university",updateObject));
		dbObjectQueryDao.update(dbObject,setObject);
	}
		/**
	 * 向数组中添加一个对象
	 * 也是更新文档的内容 所以算update
	 */
	@Test
	public void updateOnePushListTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",8);//查询条件

		DBObject pushDBObject = new BasicDBObject();//要插入的内容
		pushDBObject.put("startDate","2013-08-10");
		pushDBObject.put("endDate","2017-09-06");
		pushDBObject.put("address","深圳");
		pushDBObject.put("name","百度");

		DBObject updateObject = new BasicDBObject();//要插入哪个list
		updateObject.put("workExperience",pushDBObject);

		DBObject setObject = new BasicDBObject();
		setObject.put("$push",updateObject);//操作

		dbObjectQueryDao.update(dbObject,setObject);
	}
	/**
	 * 修改一条数据 修改文档数组中的对象
	 * 数据格式
	 {
	 "_id" : 8,
	 "name" : "小灰灰",
	 "age" : 26,
	 "sex" : "男",
	 "university" : {
	 	"name" : "北京大学",
	 	"address" : "北京"
	 },
	 "workExperience" : [{
	 	"startDate" : "2010-10-10",
	 	"endDate" : "2013-06-06",
	 	"address" : "深圳",
	 	"name" : "腾讯"
	 },{
	 	"startDate" : "2013-08-10",
	 	"endDate" : "2017-09-06",
	 	"address" : "深圳",
	 	"name" : "百度"
	 }]
	 }
	 */
	@Test
	public void updateOneInListTest(){
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id",8);

		DBObject elemMatchObject=new BasicDBObject();
		elemMatchObject.put("name","腾讯");
		dbObject.put("workExperience",new BasicDBObject().append("$elemMatch",elemMatchObject));//不能用put?
		//DBObject result=dbObjectQueryDao.findOne(dbObject); 查询符合条件的数组
		//以上为查询条件
		DBObject updateObject = new BasicDBObject();
		updateObject.put("workExperience.$.address","北京");
		DBObject setObject = new BasicDBObject();
		setObject.put("$set",updateObject);
		dbObjectQueryDao.update(dbObject,setObject);
	}

你可能感兴趣的:(mongodb)