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");
}

猜你喜欢

转载自blog.csdn.net/qq_52006948/article/details/120712031