MongoDB基本操作(三)——使用Java操作MongoDB

Java使用

添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
</dependencies>

配置属性文件(appliction.yml)

spiring:
	#数据源配置
	data:
		mongodb:
			#主机地址
			host: locahost
			#数据库
			database: test
			#默认端口时27017
			port:	27017
			#也可以使用url连接
			#url:mongodb://localhost:27017/test

添加数据

db.comment.insert({
  _id:'1',
  content:"我们不应该吧清晨浪费在手机上,哈哈",
  pulishtime :null,
  userid:'1002',
  nickname:"Aoi"
})

创建分页

在CommentReposity中添加方法

public interface CommentRepository extends MongoRepository<Comment,String>{
  //方法名根据已有字段来设置,Mongo会提示,拼写错误则无法使用
  //第一个参数是查询条件,第二个是分页
  Page<Comment> findByParentid(String parentid,Pageable pageable);
}

在Service中添加该方法

public Page<Comment> findCommentListByParentid(String parentid,int page,int size){
  //之所以-1是因为索引从0开始  
  return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));
    }

实现点赞

在Service中新增updateThumbup方法

/*
点赞-效率低
@param id
*/
public void updateCommentThumbupToIncrementingOld(String id){
  Comment comment = commentRepository.findById(id).get();
  comment.setLikenum(comment.getLikenum()+1);
  CommentRepository.save(comment);
}

以上方法效率不高,只需要将点赞数+1就可以,没必要查出所有字段以后再更新所有字段。

可以使用MongoTemplate类来实现对某列的操作

(1)修改CommentService

//注入MongoTemplate
@Autowired
private MongoTemplate mongoTemplate;

public void updateCommentLikenum(String id){
  //查询对象
  Query query = Query.query(Criteria.where("_id"),is(id));
  //更新对象
  Update update = new Update();
	//局部更新,相当于$set
  //update.set(key,value)
  //递增$inc
  // update.inc("likenum",1)
  update.inc("likenum");
  
  //参数1:查询对象
  //参数2:更新对象
  //参数3:集合的名字或实体类的类型Comment.class
  mongoTemplate.updateFirst(query,update,"comment");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值