mongodb基本操作

安装

拉取镜像

dokcer pull mogo

创建容器

docker run -di --name mongo-service --restart=always -p 27017:27017 -v ~/data/mongodata:/data mongo

项目集成

导入依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

修改application

yaml 复制代码
server:
  port: 9998
spring:
  data:
    mongodb:
      host: 192.168.200.130
      port: 27017
      database: leadnews-history

创建实体类

java 复制代码
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 * 联想词表
 * </p>
 *
 */
@Data
@Document("ap_associate_words")
public class ApAssociateWords implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    /**
     * 联想词
     */
    private String associateWords;

    /**
     * 创建时间
     */
    private Date createdTime;

}

测试类

java 复制代码
import com.itheima.mongo.MongoApplication;
import com.itheima.mongo.pojo.ApAssociateWords;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

@SpringBootTest(classes = MongoApplication.class)
@RunWith(SpringRunner.class)
public class MongoTest {


    @Autowired
    private MongoTemplate mongoTemplate;

    //保存
    @Test
    public void saveTest(){
        /*for (int i = 0; i < 10; i++) {
            ApAssociateWords apAssociateWords = new ApAssociateWords();
            apAssociateWords.setAssociateWords("黑马头条");
            apAssociateWords.setCreatedTime(new Date());
            mongoTemplate.save(apAssociateWords);
        }*/
        ApAssociateWords apAssociateWords = new ApAssociateWords();
        apAssociateWords.setAssociateWords("黑马直播");
        apAssociateWords.setCreatedTime(new Date());
        mongoTemplate.save(apAssociateWords);

    }

    //查询一个
    @Test
    public void saveFindOne(){
        ApAssociateWords apAssociateWords = mongoTemplate.findById("60bd973eb0c1d430a71a7928", ApAssociateWords.class);
        System.out.println(apAssociateWords);
    }

    //条件查询
    @Test
    public void testQuery(){
        Query query = Query.query(Criteria.where("associateWords").is("黑马头条"))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApAssociateWords> apAssociateWordsList = mongoTemplate.find(query, ApAssociateWords.class);
        System.out.println(apAssociateWordsList);
    }

    @Test
    public void testDel(){
        mongoTemplate.remove(Query.query(Criteria.where("associateWords").is("黑马头条")),ApAssociateWords.class);
    }
}

saveTest方法运行之后,

会根据spring.data.mongodb.database: leadnews-history 建立数据库

根据@Document("ap_associate_words") 作为表名

以及实体类中的id,associateWords,createdTime作为表的列

核心方法

保存或者修改

ini 复制代码
mongoTemplate.save(apAssociateWords);

查询一个对象

=

ini 复制代码
ApAssociateWords apAssociateWords = mongoTemplate.findById("60bd973eb0c1d430a71a7928", ApAssociateWords.class);

多条件查询

csharp 复制代码
Query query = Query
    .query(Criteria.where("associateWords")
    .is("黑马头条")) 
    .with(Sort
        .by(Sort.Direction.DESC,"createdTime")); 
List<ApAssociateWords> apAssociateWordsList = mongoTemplate.find(query, ApAssociateWords.class);

删除

csharp 复制代码
mongoTemplate
    .remove(Query.query(Criteria.where("associateWords")
    .is("黑马头条"))
        ,ApAssociateWords.class);

MongoRepository

创建评论dto

typescript 复制代码
import java.io.Serializable;  
import java.time.LocalDateTime;  
import java.util.Date;  
  
/**  
* 文章评论实体类  
*/  
//把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。  
//@Document(collection="mongodb 对应 collection 名")  
// 若未加 @Document ,该 bean save 到 mongo 的 comment collection  
// 若添加 @Document ,则 save 到 comment collection  
@Document(collection="comment")//可以省略,如果省略,则默认使用类名小写映射集合  
//复合索引  
@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")  
@Data  
@AllArgsConstructor  
@NoArgsConstructor  
@Accessors(chain = true)  
public class Comment implements Serializable {  
//主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫"id",则该注解可以省略,否则必须写  
@Id  
private String id;//主键  
//该属性对应mongodb的字段的名字,如果一致,则无需该注解  
@Field("content")  
private String content;//吐槽内容  
private Date publishtime;//发布日期  
//添加了一个单字段的索引  
@Indexed  
private String userid;//发布人ID  
private String nickname;//昵称  
private LocalDateTime createdatetime;//评论的日期时间  
private Integer likenum;//点赞数  
private Integer replynum;//回复数  
private String state;//状态  
private String parentid;//上级ID  
private String articleid;  
  
}

创建Repository

kotlin 复制代码
import com.example.mongodb2.po.Comment;  
import org.springframework.data.domain.Page;  
import org.springframework.data.domain.Pageable;  
import org.springframework.data.mongodb.repository.MongoRepository;  
  
/**  
* @author 飞宇千虹  
* @date 2023-07-12 14:16  
*/  
public interface CommentRepository extends MongoRepository<Comment,String> {  
  
Page<Comment> findByParentid(String parentId, Pageable pageable);  
}

调用CommentRepository方法

typescript 复制代码
import com.example.mongodb2.dto.CommentRepository;  
import com.example.mongodb2.po.Comment;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.data.domain.Page;  
import org.springframework.data.domain.PageRequest;  
import org.springframework.data.domain.Pageable;  
import org.springframework.data.mongodb.core.MongoTemplate;  
import org.springframework.data.mongodb.core.query.Criteria;  
import org.springframework.data.mongodb.core.query.Query;  
import org.springframework.data.mongodb.core.query.Update;  
import org.springframework.stereotype.Service;  
  
import java.util.List;  
  
/**  
* @author 飞宇千虹  
* @date 2023-07-12 14:17  
*/  
@Service  
public class CommentService {  
  
@Autowired  
private CommentRepository commentRepository;  
  
/**  
* 保存一个评论  
* @param comment  
*/  
public void saveComment(Comment comment){  
//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键  
//设置一些默认初始值。。。  
//调用dao  
commentRepository.save(comment);  
}  
  
/**  
* 更新评论  
* @param comment  
*/  
public void updateComment(Comment comment){  
//调用dao  
commentRepository.save(comment);  
}  
  
/**  
* 根据id删除评论  
* @param id  
*/  
public void deleteCommentById(String id){  
//调用dao  
commentRepository.deleteById(id);  
}  
  
/**  
* 查询所有评论  
* @return  
*/  
public List<Comment> findCommentList(){  
//调用dao  
return commentRepository.findAll();  
}  
  
/**  
* 根据id查询评论  
* @param id  
* @return  
*/  
public Comment findCommentById(String id){  
//调用dao  
return commentRepository.findById(id).get();  
}  
  
  
public Page<Comment> findByParentId(String parentId,int page ,int size){  
return commentRepository.findByParentid(parentId,PageRequest.of(page-1,size));  
}  
  
@Autowired  
private MongoTemplate mongoTemplate;  
  
public void updateCommentLikenum(String id){  
// 查询条件  
Query query = Query.query(Criteria.where("_id").is(id));  
// 更新条件  
Update update = new Update();  
update.inc("likenum");  
  
mongoTemplate.updateFirst(query,update,Comment.class);  
}  
  
}

方法测试

java 复制代码
import com.example.mongodb2.po.Comment;  
import com.example.mongodb2.service.CommentService;  
import org.junit.jupiter.api.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.boot.test.context.SpringBootTest;  
import org.springframework.data.domain.Page;  
import org.springframework.data.mongodb.core.MongoTemplate;  
import org.springframework.test.context.junit4.SpringRunner;  
  
import java.util.List;  
  
@RunWith(SpringRunner.class)  
@SpringBootTest  
class Mongodb2ApplicationTests {  
  
@Autowired  
private CommentService commentService;  
  
@Autowired  
private MongoTemplate mongoTemplate;  
  
@Test  
void contextLoads() {  
List<Comment> commentList = commentService.findCommentList();  
System.out.println(commentList);  
}  
  
@Test  
void getOne() {  
Comment commentById = commentService.findCommentById("1");  
System.out.println(commentById);  
}  
  
@Test  
void page() {  
Page<Comment> page = commentService.findByParentId("3", 1, 2);  
System.out.println(page.getTotalPages());  
System.out.println(page.getContent());  
}  
  
@Test  
void updateCommentLikenum() {  
commentService.updateCommentLikenum("1");  
  
}  
}

查询评论列表

csharp 复制代码
@Test  
void contextLoads() {  
List<Comment> commentList = commentService.findCommentList();  
System.out.println(commentList);  
}  

根据id查询评论信息

csharp 复制代码
  
@Test  
void getOne() {  
Comment commentById = commentService.findCommentById("1");  
System.out.println(commentById);  
} 

查询分页信息

csharp 复制代码
@Test  
void page() {  
Page<Comment> page = commentService.findByParentId("3", 1, 2);  
System.out.println(page.getTotalPages());  
System.out.println(page.getContent());  
} 

为指定id的评论添加点赞

typescript 复制代码
@Test  
void updateCommentLikenum() {  
    commentService.updateCommentLikenum("1");  
}  

方法执行前 方法执行后

相关推荐
一弓虽10 分钟前
SpringBoot 学习
java·spring boot·后端·学习
姑苏洛言19 分钟前
扫码小程序实现仓库进销存管理中遇到的问题 setStorageSync 存储大小限制错误解决方案
前端·后端
光而不耀@lgy34 分钟前
C++初登门槛
linux·开发语言·网络·c++·后端
方圆想当图灵1 小时前
由 Mybatis 源码畅谈软件设计(七):SQL “染色” 拦截器实战
后端·mybatis·代码规范
毅航1 小时前
MyBatis 事务管理:一文掌握Mybatis事务管理核心逻辑
java·后端·mybatis
我的golang之路果然有问题2 小时前
速成GO访问sql,个人笔记
经验分享·笔记·后端·sql·golang·go·database
柏油2 小时前
MySql InnoDB 事务实现之 undo log 日志
数据库·后端·mysql
写bug写bug3 小时前
Java Streams 中的7个常见错误
java·后端
Luck小吕4 小时前
两天两夜!这个 GB28181 的坑让我差点卸载 VSCode
后端·网络协议
M1A14 小时前
全栈开发必备:Windows安装VS Code全流程
前端·后端·全栈