5-MongoDB实战演练

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
简介: 本项目基于SpringDataMongoDB实现头条文章评论功能,涵盖增删改查、按文章ID查询评论及点赞功能。通过MongoTemplate优化点赞操作,提升性能,并使用索引提高查询效率,构建高效可扩展的微服务模块。

5.1 需求分析
某头条的文章评论业务如下:
需要实现以下功能:
1)基本增删改查API
2)根据文章id查询评论
3)评论点赞

5.2 表结构分析
数据库:articledb

5.3 技术选型
5.3.1 mongodb-driver(了解)
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们通过一个入门的案例来了解mongodb-driver的基本使用。
官方驱动说明和下载:链接 ,官方驱动示例文档:链接。
5.3.2 SpringDataMongoDB
SpringData家族成员之一,用于操作MongoDB的持久层框架,封装了底层的mongodb-driver。
官网主页: https://projects.spring.io/spring-data-mongodb/
5.4 文章微服务模块搭建
(1)搭建项目工程article,pom.xml引入依赖:
<?xml version="1.0" encoding="UTF-8"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE


cn.itcast
article
1.0-SNAPSHOT


org.springframework.boot
spring-boot-starter-test
test


org.springframework.boot
spring-boot-starter-data-mongodb



(2)创建application.yml
spring:

数据源配置

data:
mongodb:

  # 主机地址
  host: 192.168.40.141
  # 数据库
  database: articledb
  # 默认端口是27017
  port: 27017
  #也可以使用uri连接
  #uri: mongodb://192.168.40.134:27017/articledb

(3)创建启动类
cn.itcast.article.ArticleApplication
package cn.itcast.article;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class, args);
}
}
(4)启动项目,看是否能正常启动,控制台没有错误。
5.5 文章评论实体类的编写
创建实体类 创建包cn.itcast.article,包下建包po用于存放实体类,创建实体类
cn.itcast.article.po.Comment
package cn.itcast.article.po;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
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}")
    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;
    //getter and setter.....
    public String getId() {

      return id;
    

    }
    public void setId(String id) {

      this.id = id;
    

    }
    public String getContent() {

      return content;
    

    }
    public void setContent(String content) {

      this.content = content;
    

    }
    public Date getPublishtime() {

      return publishtime;
    

    }
    public void setPublishtime(Date publishtime) {

      this.publishtime = publishtime;
    

    }
    public String getUserid() {

      return userid;
    

    }
    public void setUserid(String userid) {

      this.userid = userid;
    

    }
    public String getNickname() {

      return nickname;
    

    }
    public void setNickname(String nickname) {

      this.nickname = nickname;
    

    }
    public LocalDateTime getCreatedatetime() {

      return createdatetime;
    

    }
    public void setCreatedatetime(LocalDateTime createdatetime) {

      this.createdatetime = createdatetime;
    

    }
    public Integer getLikenum() {

      return likenum;
    

    }
    public void setLikenum(Integer likenum) {

      this.likenum = likenum;
    

    }
    public Integer getReplynum() {

      return replynum;
    

    }
    public void setReplynum(Integer replynum) {

      this.replynum = replynum;
    

    }
    public String getState() {

      return state;
    

    }
    public void setState(String state) {

      this.state = state;
    

    }
    public String getParentid() {

      return parentid;
    

    }
    public void setParentid(String parentid) {

      this.parentid = parentid;
    

    }
    public String getArticleid() {

      return articleid;
    

    }
    public void setArticleid(String articleid) {

      this.articleid = articleid;
    

    }

    @Override
    public String toString() {

      return "Comment{" +
      "id='" + id + '\'' +
      ", content='" + content + '\'' +
      ", publishtime=" + publishtime +
      ", userid='" + userid + '\'' +
      ", nickname='" + nickname + '\'' +
      ", createdatetime=" + createdatetime +
      ", likenum=" + likenum +
      ", replynum=" + replynum +
      ", state='" + state + '\'' +
      ", parentid='" + parentid + '\'' +
      ", articleid='" + articleid + '\'' +
      '}';
    

    }
    }
    说明:
    索引可以大大提升查询效率,一般在查询字段上添加索引,索引的添加可以通过Mongo的命令来添加,也可以在Java的实体类中通过注解添加。
    1)单字段索引注解@Indexed
    org.springframework.data.mongodb.core.index.Indexed.class
    声明该字段需要索引,建索引可以大大的提高查询效率。
    Mongo命令参考:
    db.comment.createIndex({"userid":1})
    2)复合索引注解@CompoundIndex
    org.springframework.data.mongodb.core.index.CompoundIndex.class
    复合索引的声明,建复合索引可以有效地提高多字段的查询效率。
    Mongo命令参考:
    db.comment.createIndex({"userid":1,"nickname":-1})
    5.6 文章评论的基本增删改查
    (1)创建数据访问接口 cn.itcast.article包下创建dao包,包下创建接口
    cn.itcast.article.dao.CommentRepository
    package cn.itcast.article.dao;

import cn.itcast.article.po.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;

//评论的持久层接口
public interface CommentRepository extends MongoRepository {

}
(2)创建业务逻辑类 cn.itcast.article包下创建service包,包下创建类
cn.itcast.article.service.CommentService
package cn.itcast.article.service;

import cn.itcast.article.dao.CommentRepository;
import cn.itcast.article.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

//评论的业务层
@Service
public class CommentService {

//注入dao
@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();
}

}
(3)新建Junit测试类,测试保存和查询所有:
cn.itcast.article.service.CommentServiceTest
package cn.itcast.article.service;

import cn.itcast.article.ArticleApplication;
import cn.itcast.article.po.Comment;
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.Page;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.List;

//测试评论的业务层
//SpringBoot的Junit集成测试
@RunWith(SpringRunner.class)
//SpringBoot的测试环境初始化,参数:启动类
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {

//注入Service
@Autowired
private CommentService commentService;

/**
 * 保存一个评论
 */
@Test
public void testSaveComment(){
    Comment comment=new Comment();
    comment.setArticleid("100000");
    comment.setContent("测试添加的数据");
    comment.setCreatedatetime(LocalDateTime.now());
    comment.setUserid("1003");
    comment.setNickname("凯撒大帝");
    comment.setState("1");
    comment.setLikenum(0);
    comment.setReplynum(0);
    commentService.saveComment(comment);
}

/**
 * 查询所有数据
 */
@Test
public void testFindAll(){
    List<Comment> list = commentService.findCommentList();
    System.out.println(list);
}

/**
 * 测试根据id查询
 */
@Test
public void testFindCommentById(){
    Comment comment = commentService.findCommentById("5d6a27b81b8d374798cf0b41");
    System.out.println(comment);
}

}
添加结果:

5.7 根据上级ID查询文章评论的分页列表
(1)CommentRepository新增方法定义
//根据父id,查询子评论的分页列表
Page findByParentid(String parentid, Pageable pageable);<br>(2)CommentService新增方法<br>/**</p> <ul> <li>根据父id查询分页列表</li> <li>@param parentid</li> <li>@param page</li> <li>@param size</li> <li>@return<br><em>/<br>public Page<Comment> findCommentListPageByParentid(String parentid,int page ,int size){<br> return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));<br>}<br>(3)junit测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em><ul> <li>测试根据父id查询子评论的分页列表<br>*/<br>@Test<br>public void testFindCommentListPageByParentid(){<br>Page<Comment> pageResponse = commentService.findCommentListPageByParentid(&quot;3&quot;, 1, 2);<br>System.out.println(&quot;----总记录数:&quot;+pageResponse.getTotalElements());<br>System.out.println(&quot;----当前页数据:&quot;+pageResponse.getContent());<br>}<br>(4)测试<br>使用compass快速插入一条测试数据,数据的内容是对3号评论内容进行评论。</li> </ul> </li> </ul> <p>执行测试,结果:<br>----总记录数:1<br>----当前页数据:[Comment{id=&#39;33&#39;, content=&#39;你年轻,火力大&#39;, publishtime=null, userid=&#39;1003&#39;, nickname=&#39;凯撒大帝&#39;, createdatetime=null, likenum=null, replynum=null, state=&#39;null&#39;, parentid=&#39;3&#39;, articleid=&#39;100001&#39;}]<br>5.8 MongoTemplate实现评论点赞<br>我们看一下以下点赞的临时示例代码: CommentService 新增updateThumbup方法<br>/**</p> <ul> <li>点赞-效率低</li> <li>@param id<br>*/<br>public void updateCommentThumbupToIncrementingOld(String id){<br> Comment comment = CommentRepository.findById(id).get();<br> comment.setLikenum(comment.getLikenum()+1);<br> CommentRepository.save(comment);<br>}<br>以上方法虽然实现起来比较简单,但是执行效率并不高,因为我只需要将点赞数加1就可以了,没必要查询出所有字段修改后再更新所有字段。我们可以使用MongoTemplate类来实现对某列的操作。<br>(1)修改CommentService<br>//注入MongoTemplate<br>@Autowired<br>private MongoTemplate mongoTemplate;</li> </ul> <p>/**</p> <ul> <li>点赞数+1</li> <li>@param id<br><em>/<br>public void updateCommentLikenum(String id){<br> //查询对象<br> Query query=Query.query(Criteria.where(&quot;_id&quot;).is(id));<br> //更新对象<br> Update update=new Update();<br> //局部更新,相当于$set<br> // update.set(key,value)<br> //递增$inc<br> // update.inc(&quot;likenum&quot;,1);<br> update.inc(&quot;likenum&quot;);<br> //参数1:查询对象<br> //参数2:更新对象<br> //参数3:集合的名字或实体类的类型Comment.class<br> mongoTemplate.updateFirst(query,update,&quot;comment&quot;);<br>}<br>(2)测试用例:<br>cn.itcast.article.service.CommentServiceTest<br>/*</em></li> <li>点赞数+1<br>*/<br>@Test<br>public void testUpdateCommentLikenum(){<br> //对3号文档的点赞数+1<br> commentService.updateCommentLikenum(&quot;3&quot;);<br>}<br>执行测试用例后,发现点赞数+1了:</li> </ul>

相关文章
|
11天前
|
人工智能 自然语言处理 Shell
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
本教程指导用户在开源AI助手Clawdbot中集成阿里云百炼API,涵盖安装Clawdbot、获取百炼API Key、配置环境变量与模型参数、验证调用等完整流程,支持Qwen3-max thinking (Qwen3-Max-2026-01-23)/Qwen - Plus等主流模型,助力本地化智能自动化。
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
|
7天前
|
人工智能 安全 机器人
OpenClaw(原 Clawdbot)钉钉对接保姆级教程 手把手教你打造自己的 AI 助手
OpenClaw(原Clawdbot)是一款开源本地AI助手,支持钉钉、飞书等多平台接入。本教程手把手指导Linux下部署与钉钉机器人对接,涵盖环境配置、模型选择(如Qwen)、权限设置及调试,助你快速打造私有、安全、高权限的专属AI助理。(239字)
4281 12
OpenClaw(原 Clawdbot)钉钉对接保姆级教程 手把手教你打造自己的 AI 助手
|
8天前
|
人工智能 机器人 Linux
保姆级 OpenClaw (原 Clawdbot)飞书对接教程 手把手教你搭建 AI 助手
OpenClaw(原Clawdbot)是一款开源本地AI智能体,支持飞书等多平台对接。本教程手把手教你Linux下部署,实现数据私有、系统控制、网页浏览与代码编写,全程保姆级操作,240字内搞定专属AI助手搭建!
4668 16
保姆级 OpenClaw (原 Clawdbot)飞书对接教程 手把手教你搭建 AI 助手
|
6天前
|
人工智能 机器人 Linux
OpenClaw(Clawdbot、Moltbot)汉化版部署教程指南(零门槛)
OpenClaw作为2026年GitHub上增长最快的开源项目之一,一周内Stars从7800飙升至12万+,其核心优势在于打破传统聊天机器人的局限,能真正执行读写文件、运行脚本、浏览器自动化等实操任务。但原版全英文界面对中文用户存在上手门槛,汉化版通过覆盖命令行(CLI)与网页控制台(Dashboard)核心模块,解决了语言障碍,同时保持与官方版本的实时同步,确保新功能最快1小时内可用。本文将详细拆解汉化版OpenClaw的搭建流程,涵盖本地安装、Docker部署、服务器远程访问等场景,同时提供环境适配、问题排查与国内应用集成方案,助力中文用户高效搭建专属AI助手。
2979 8
|
10天前
|
人工智能 JavaScript 应用服务中间件
零门槛部署本地AI助手:Windows系统Moltbot(Clawdbot)保姆级教程
Moltbot(原Clawdbot)是一款功能全面的智能体AI助手,不仅能通过聊天互动响应需求,还具备“动手”和“跑腿”能力——“手”可读写本地文件、执行代码、操控命令行,“脚”能联网搜索、访问网页并分析内容,“大脑”则可接入Qwen、OpenAI等云端API,或利用本地GPU运行模型。本教程专为Windows系统用户打造,从环境搭建到问题排查,详细拆解全流程,即使无技术基础也能顺利部署本地AI助理。
7196 16
|
8天前
|
存储 人工智能 机器人
OpenClaw是什么?阿里云OpenClaw(原Clawdbot/Moltbot)一键部署官方教程参考
OpenClaw是什么?OpenClaw(原Clawdbot/Moltbot)是一款实用的个人AI助理,能够24小时响应指令并执行任务,如处理文件、查询信息、自动化协同等。阿里云推出的OpenClaw一键部署方案,简化了复杂配置流程,用户无需专业技术储备,即可快速在轻量应用服务器上启用该服务,打造专属AI助理。本文将详细拆解部署全流程、进阶功能配置及常见问题解决方案,确保不改变原意且无营销表述。
4914 5
|
10天前
|
人工智能 JavaScript API
零门槛部署本地 AI 助手:Clawdbot/Meltbot 部署深度保姆级教程
Clawdbot(Moltbot)是一款智能体AI助手,具备“手”(读写文件、执行代码)、“脚”(联网搜索、分析网页)和“脑”(接入Qwen/OpenAI等API或本地GPU模型)。本指南详解Windows下从Node.js环境搭建、一键安装到Token配置的全流程,助你快速部署本地AI助理。(239字)
4807 23
|
16天前
|
人工智能 API 开发者
Claude Code 国内保姆级使用指南:实测 GLM-4.7 与 Claude Opus 4.5 全方案解
Claude Code是Anthropic推出的编程AI代理工具。2026年国内开发者可通过配置`ANTHROPIC_BASE_URL`实现本地化接入:①极速平替——用Qwen Code v0.5.0或GLM-4.7,毫秒响应,适合日常编码;②满血原版——经灵芽API中转调用Claude Opus 4.5,胜任复杂架构与深度推理。
8935 13