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

方法执行前 方法执行后

相关推荐
凡人的AI工具箱6 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
是店小二呀6 小时前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
canonical_entropy6 小时前
金蝶云苍穹的Extension与Nop平台的Delta的区别
后端·低代码·架构
我叫啥都行7 小时前
计算机基础知识复习9.7
运维·服务器·网络·笔记·后端
无名指的等待7128 小时前
SpringBoot中使用ElasticSearch
java·spring boot·后端
.生产的驴8 小时前
SpringBoot 消息队列RabbitMQ 消费者确认机制 失败重试机制
java·spring boot·分布式·后端·rabbitmq·java-rabbitmq
AskHarries9 小时前
Spring Boot利用dag加速Spring beans初始化
java·spring boot·后端
苹果酱05679 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
掐指一算乀缺钱9 小时前
SpringBoot 数据库表结构文档生成
java·数据库·spring boot·后端·spring
计算机学姐12 小时前
基于python+django+vue的影视推荐系统
开发语言·vue.js·后端·python·mysql·django·intellij-idea