MongoDB的使⽤MongoTemplate操作增删改查,分页,排序,聚合(含内嵌数
据)。。。
⽬录
MongoDB简单介绍
MongoDB是⼀个开源、⾼性能、⽆模式的⽂档型数据库,当初的设计就是⽤于简化开发和⽅便扩展,是NoSQL数据库产品中的⼀种。是最像关系型数据库(MySQL)的⾮关系型数据库。
它⽀持的数据结构⾮常松散,是⼀种类似于 JSON 的 格式叫BSON,所以它既可以存储⽐较复杂的数据类型,⼜相当的灵活。
依赖包
<!--springboot是2.1.6.RELEASE-->
<!--操作MongoDB核⼼包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!--简化实体类和⽇志的操作-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
yml简单配置
spring:
data:
mongodb:
host:192.168.142.139
database: articledb#数据库名
port:27017
#也可以使⽤uri连接
#uri: mongodb://192.168.142.139:27017/articledb
实体类
@Data//相当于get/set⽅法
@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;
private List<User> users;//⾃⼰建⽴的⼀个实体类User测试内嵌数据
}
⾮内嵌形式
增(insert)
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Comment insert(Comment comment){
log.info("简单的新增开始");
Comment insert = mongoTemplate.insert(comment);
return insert;
}
添加多条记录
mongoTemplate.insert(数据结合,Comment.class);
删(remove)
根据实体类对象删除测试只有设定id才可以
@Override
public Long removeObj(){
log.info("removeObj()");
Comment comment =new Comment();
comment.setId("1");
DeleteResult remove = ve(comment);
long deletedCount = DeletedCount();
return deletedCount;
}
根据条件删除(Query对象)推荐使⽤这个
public Long removeQuery(){
log.info("removeQuery");
Query query =new Query();
//把userid==100的删除
Criteria criteria = Criteria.where("userid").is("100");
query.addCriteria(criteria);
DeleteResult remove = ve(query, Comment.class);
DeletedCount();
}
改(updateFirst|updateMulti)
mongoTemplate.updateFirst(query, update, Comment.class);更新匹配的第⼀条数据
@Override
public Long updateFirstComment(){
log.info("updateFirstComment");
Query query = Query.query(Criteria.where("userid").is("1003"));
Update update =new Update();
update.set("nickname","updateFirstComment");
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
System.out.MatchedCount());
MatchedCount();
}
UpdateResult updateMulti(Query query, Update update, Class<?> entityClass);更新匹配条件的全部数据
@Override
public Long updateMultiComment(){
log.info("updateMultiComment");
Query query = Query.query(Criteria.where("userid").is("1003"));
Update update =new Update();
update.set("nickname","updateMultiComment");
UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Comment.class);
System.out.MatchedCount());
MatchedCount();
}
UpdateResult upsert(Query var1, Update var2, Class<?> var3);如果数据不存在就增加⼀条
查
查全部结果(findAll)
@Override
public List<Comment>findAll(){
//Comment.class实体类的class对象
log.info("findAll");
List<Comment> all = mongoTemplate.findAll(Comment.class);
return all;
}
条件查询–或(or)
Criteria criteria1 =new Criteria();
criteria1.and("users.id").is("001");
//条件⼆
Criteria criteria2 =new Criteria();
criteria2.and("userid").is("1003");
//把条件或起来
Criteria criteria =new Criteria();
Query query =new Query();
query.addCriteria(criteria);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
return comments;
}
条件查询–且(and)
@Override
public List<Comment>findQueryComment(){
Criteria criteria =new Criteria();
//且⽐或简单
criteria.and("users.id").is("1").and("userid").is("100");
Query query =new Query();
query.addCriteria(criteria);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
return comments;
}
条件查询-模糊查询(regex)
@Override
public List<Comment>findQueryComment(){
Query query =new Query();
Criteria criteria =new Criteria();
//正则
criteria.and("userid").regex("^.*"+0+".*$");
query.addCriteria(criteria);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
return comments;
}
条件查询-查总数(count )
@Override
public Long findQueryComment(){
mongodb和mysql结合Query query =new Query();
Criteria criteria =new Criteria();
//正则
criteria.and("userid").regex("^.*"+0+".*$");
query.addCriteria(criteria);
long count = unt(query, Comment.class);
return count;
}
条件查询-排序(sort)
Query query = Query.query(Criteria.where("userid").is("1003"));
//排序规则把id倒序
Sort sort =new Sort(Sort.Direction.DESC,"_id");
query.with(sort);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
return comments;
}
条件查询-分页(Pageable)
@Override
public List<Comment>findQueryComment(){
//条件体
Query query =new Query();
//排序规则把id倒序
Sort sort =new Sort(Sort.Direction.DESC,"_id");
//当前页+页的⼤⼩(当前页应该是实际页数减⼀)
PageRequest page = PageRequest.of(0,2);
query.with(sort);
//分页 ===也可以⽤query.skip(当前页-1).limit(页的⼤⼩)
query.with(page);
List<Comment> comments = mongoTemplate.find(query, Comment.class);
return comments;
}
聚合查询(Aggregation )
Criteria criteria =new Criteria();
criteria.and("users.id").is("1").and("userid").is("100");
//up("userid").count().as("total")
//count 聚合函数(和SQL⼀样)
Aggregation aggregation = wAggregation(Aggregation.match(criteria),
Aggregation.sort(Sort.Direction.DESC,"total"));
//comment表名 JSONObject.class返回的类型,可以⾃⾏封装实体类属性名要和聚合的别名⼀样才可
以注⼊,类似mybatis AggregationResults<JSONObject> aggregate = mongoTemplate.aggregate(aggregation,
"comment", JSONObject.class);
List<JSONObject> Comments = MappedResults();
内嵌增加数据
如果想在users的集合⾥加⼀条数据怎么办?
{
"_id":"5eec4eaeefe450068c1dc854",
"content":"我是简单的增加",
"userid":"100",
"createdatetime":"2020-06-19T05:35:42.389Z",
"likenum":10,
"parentid":"1003",
"articleid":"100",
"users":[
{
"_id":"1",
"name":"⼩明"
}
],
"_class":"db.pojo.Comment"
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论