mongodb的简单使用三(结合springdata 使用遇到的坑)

总结springdata+mongodb开发的小经验


接着上一篇文章《 mongodb的简单使用二(结合springdata实现增删改查)》写一下总结
       
1、查询操作:
      a)查询制定字段的:通过这种方式  query.fields().include("userId");
 Query query = new Query();
		query.fields().include("userId");
		query.fields().include("images");
		query.fields().include("content");
		query.fields().include("createTime");
		query.fields().include("publicFlag");
		query.fields().include("favorCount");
		query.fields().include("commentCount");
		query.fields().include("status");
		query.fields().include("type");
		query.fields().include("childId");
		query.fields().include("happenedDay");
		query.fields().include("mood");
		query.fields().include("imageProportions");


     b)查询条件“>”, "<", ">=", "<=" : 使用如下代码  gt,lt,gte,lte
    
if(paramBean.getFrom()==0){
				//查询发现记录列表,按发布时间排序
				if(paramBean.getThan() == 0){
					//下拉刷新
					listCriteria.add(Criteria.where("createTime").gt(paramBean.getCreateTime()));
				}else if(paramBean.getThan() == 1){
					//上拉加载更多
					listCriteria.add(Criteria.where("createTime").lt(paramBean.getCreateTime()));
				}
		}



2、删除操作
    
      a)根据条件删除数据
	/**
	 * 通过记录的ObjectiId删除评论
	 * @param _id
	 */
	public void deleteCommentsByRecordId(String recordId){
		Query query = new Query(Criteria.where("recordId").is(recordId));
		this.delete(query, RecordComment.class);
	}



      b)删除内嵌文档
	/**
	 * 删除用户孩子已经统计的能力值
	 * @param userId
	 * @param childId
	 * @param itemType
	 */
	public void deleteItemType(Long userId,Long childId,String itemType){
		Query query = new Query(Criteria.where("userId").is(userId).and("childId").is(childId));
		Update update = new Update();
		update.pull("itemType", itemType);
		this.updateFirst(query, update, AbilityStatistics.class);
	}

        在mongodb控制台中对内嵌文档的删除:示例
       

使用"$pull",可以根据特定条件删除元素,也可以根据位置删除元素

db.users.update(

   {"userName":"refactor"},
   {
     "$pull":
     {
       "emails":"295240648@111.com"
     }
   }
)

"$pull"会将所有匹配的部分删掉,对于数组[1,1,2,1]执行pull 1,得到的结果数组是[2]


3.新增操作:(内嵌文档)

    a)主要是调用save方法,下面的示例中,包含了内嵌文档的新增和更新
	/**
	 * 统计孩子的能力值,先判断数据库中是否有记录,有则更新记录的itemType数组,没有则新增一条记录,并且加入itemType
	 * @param userId
	 * @param childId
	 * @param itemType
	 */
	public void addItemSet(Long userId,Long childId,String itemType){
		AbilityStatistics abilityStatistics = this.findByUserIdAndChildId(userId, childId);
		Query query = new Query(Criteria.where("userId").is(userId).and("childId").is(childId));
		Update update = new Update();
		if(abilityStatistics!=null){
			List<String> typeList = abilityStatistics.getItemType();
			//条目中不存在则新增,存在就不做新增条目类型操作
			if(typeList != null && typeList.size() > 0 && !typeList.contains(itemType)){
				//后续更改新增类型
				update.addToSet("itemType", itemType);
				this.updateFirst(query, update, AbilityStatistics.class);
			}else if(typeList==null || typeList.size()==0 ){
				//第一次添加type数组
				update.addToSet("itemType", itemType);
				this.updateFirst(query, update, AbilityStatistics.class);
			}
		}else{
			abilityStatistics = new AbilityStatistics();
			abilityStatistics.setChildId(childId);
			abilityStatistics.setUserId(userId);
			List<String> itemTypes = new ArrayList<String>();
			itemTypes.add(itemType);
			abilityStatistics.setItemType(itemTypes);
			this.save(abilityStatistics);
		}
	}



4、修改操作(update),修改的时候需要注意两个点 1:query 条件  2:update数据操作set

    a)根据条件修改特定的字段的值。代码示例
    
	/**
	 * 重新发布记录
	 */
	public void updateRecordByReuploads(Record updateRecord){
		Query query = new Query();
		Criteria criteria = new Criteria();
		String recordId = null;
		//我的记录列表页跳转的时候客户端传递参数_id主键
		if(!StringUtil.isEmpty(updateRecord.get_id())){
			query = Query.query(Criteria.where("_id").is(updateRecord.get_id()));
			recordId = updateRecord.get_id();
		}else{
			//在记录发布界面,点击条目发表记录,传入参数userId,childId,type(Map)
			//查询条件
			List<Criteria> listCriteria = new ArrayList<Criteria>();
			listCriteria.add(Criteria.where("userId").is(updateRecord.getUserId()));
			listCriteria.add(Criteria.where("childId").is(updateRecord.getChildId()));
			listCriteria.add(Criteria.where("type.ptype").is(updateRecord.getType().get("ptype")));
			listCriteria.add(Criteria.where("type.fctype").is(updateRecord.getType().get("fctype")));
			listCriteria.add(Criteria.where("type.sctype").is(updateRecord.getType().get("sctype")));
			 //转换条件查询
			Criteria[] criteriaCondition = listCriteria.toArray(new Criteria[listCriteria.size()]);
			criteria.andOperator(criteriaCondition);
			query.addCriteria(criteria);
			
			List<Record> tempList = this.findByQuery(query, Record.class);
			if(tempList!=null && tempList.size()>0 && tempList.get(0)!=null){
				recordId = tempList.get(0).get_id();
			}
		}
		
		Update update = new Update();
		update.set("publicFlag", updateRecord.getPublicFlag());
		update.set("content", updateRecord.getContent());
		update.set("createTime", new Date().getTime());
		update.set("mood", updateRecord.getMood());
		update.set("happenedDay", updateRecord.getHappenedDay());
		update.set("images", updateRecord.getImages());
		update.set("imageProportions", updateRecord.getImageProportions());
		update.set("favorCount", 0);
		update.set("commentCount", 0);
		update.set("status", 0);
		this.updateFirst(query, update, Record.class);
		if(recordId!=null){
			//删除评论表中该条记录的所有评论
			recordCommentDao.deleteCommentsByRecordId(recordId);
		}
	}



       b)对字段做 "加",“减” 操作,使用 inc() 方法,代码示例
	/**
	 * 新增评论,评论数+1
	 * @param _id
	 * @param comments
	 */
	public void addComments(RecordComment comments){
		Query query = Query.query(Criteria.where("_id").is(comments.get_id()));
		Update update = new Update();
                update.addToSet("comments", comments);
                update.inc("commentCount", 1);
                this.updateFirst(query, update, Record.class);
	}



       c)内嵌文档的更新.

mongodb数据库中的数据如下:

      {

    "_id": ObjectId("5550622dfc194b340a1feb5f"),
    "name": "hsaflkjhdf",
    "desc": "dfsafsdafsafad",
    "type": "微企模板",
    "template": [
        {
            "_id": ObjectId("5550d3280a706d025d8eb5d6"),
            "view": "aaaaaaaaaaa",
            "image": "http://127.0.0.1:7012/staticdata/newsdata/template/images/redare/5550622dfc194b340a1feb5f/143136029221214278739681.jpg"
        }
    ]
}

Update update =new Update();
update.set("template.$.view", view);
update.set("template.$.image", imagePath);
Query query = Query.query(new Criteria().andOperator(Criteria.where("id").is(viewTemplateId),Criteria.where("template").elemMatch(Criteria.where("id").is(templateId))));
return db.updateFirst(query, update, ViewTemplate.class);





       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值