• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

03.mongodb和java配合使用

武飞扬头像
默默努力的小老弟
帮助1

1.索引(先查索引后后查真实的数据)
mongo btree
mysql b tree

1.单字段索引
2.复合索引
3.其他索引 地理空间,文本索引,哈希索引

2.查看索引

 db.comment.getIndexes(); // v代表索引引擎版本号
//key的_id是升序排序的
//name索引的名称默认是 字段名_
// ns namespace放在那个命名空间里`在这里插入代码片`

3.创建索引

   db.comment.createIndex(keys,options);
   //建立升序的索引,升序降序不影响查询效率
   db.comment.createIndex({userid:-1});
    //建立复合索引
    db.comment.createIndex({userid:-1,nickname:-1});

4.删除索引

 db.comment.dropIndex({userid:-1,nickname:-1})
  //文本索引使用名称,或者说通过索引名删除
 db.comment.dropIndex("userid")
 //删除所有索引,_id不会删除
  db.comment.dropIndexes();

5.执行计划(查看耗费时间,索引是否生效)

   db.comment.find({userid:"10003"}).explain();
   //COLLSCAN集合扫描,代表全局扫描,没有使用索引 ,加之后stage变FETCH
部分扫描
   db.comment.createIndex({userid:1})

6.涵盖查询(了解)第二个括号是也是查询的条件(投影project), 直接在投影写的结果找,不去本表找,(投影直接有我对应的数据)

   db.comment.find({score:{$lt: 30}},{score:1})

7.文章评论

1.java mongodb-driver(相当于jdbc驱动)
2.springDataMongoDB(相当于mybatis简化操作)

8.springboot项目搭建

  1. 复制pom文件,从pom文件开始复制
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
  1. 复制yml文件
  spring:
     data:
       mongodb:
             host: 192.168.40.141
             database: articledb
             port: 27017

3.启动 启动类,看是否连接成功 日志有connention to代表成功;

4.实体类的编写

 @Document(collection="comment")  //没有指定那为类名小写   !!!有个差不多的叫colletion
   @CompoundIndex(def ="{'userid':1,'nickname':-1}")  //复合索引,通过命令行方式建(推荐)
    public class Comment implements Serialzable{
         @Id  //指定id,如果名字为id可不写
         private String id;
         @Field("content")  //代表,如果名字与db不一致可以指向(其他可以不写@field)
          private String content;
          private Date publishtime;
         @Indexed   //指定索引
         private String userid;

   }
5.增删改查 建dao和service文件夹(和MyBatisPlus一样也是继承一个类....)
   //dao建,接口继承接口用extends
   public interface CommentDao extends MongoRepository<Comment,String>{ //第一个随便修改,第二个是id的数据类型
}
 //service建
 @Service
 public class CommentService{
         @Autowired
         private CommentRepository commentRepository;
         //文档复制过来
 }
6.测试一下(注意test文件夹的包名要与service的包名保持一致,不然报错)
  如: main下有top.jamsee包,则test也要有这个目录
  @RunWith(SpringRunner.class)
  @SpringBootTest
  public class CommentServiceTest{
       @Autowired
       private CommentService commentService;
      @Test
       public void testFindCommentList(){
List<Comment> commentList =commentService.findCommentList();
               sout(commentList);
          //设置时间要注意的点
          //comment.setCreatedatetime(LocalDateTime.now());


       }

  }
学新通

9.根据上级id查询文章评论的分页列表

    //去CommentRepository写个我们的业务方法,方法名字不能乱写
   //Parentid会变成字段
public interface CommentDao extends MongoRepository<Comment,String> {
    Page<Comment> findByUserid(String parentid, Pageable pageable);

}
//去service写方法
 public Page<Comment> findByUserid(String parentid,int page ,int size){
        return commentDao.findByUserid(parentid, PageRequest.of(page-1,size));
    }

//在test测试

   commentService.findCommentListByParentid("3",1,2);
   page.getTotalElements(); //元素个数
   page.getContent();         //list集合

10.点赞
//低性能,先得到原始数据后修改他,保存

  Comment comment=CommentDao.findById(id).get();
     comment.setLikenum(comment.getLikenum() 1);
     commentDao.save(comment);

//高性能,使用springdata-monogo提供的工具Query,只执行一次

     @Autowired
    private MongoTemplate mongoTemplate;
    @Test
    public void testIncr(){
        Query query=Query.query(Criteria.where("_id").is("2"));
        Update update=new Update();
        update.inc("likenum");

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
        System.out.println(updateResult);

    }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgachge
系列文章
更多 icon
同类精品
更多 icon
继续加载