MongoDB 下载安装与启动
MongoDB下载地址 注意:win7最高适用MongoDB 4.2版本
- 下载压缩文件,在文件夹中新建data\db文件夹用来存储数据
- 启动服务器 。在bin目录启动cmd 输入mongod --dbpath=…\data\db
- 启动客户端 。 在bin目录启动cmd 输入mongo
MongoDB基础操作
db.集合名称.insert/save/insertOne(文档) //添加
db.集合名称.update({条件},{操作种类:{文档}})
db.集合名称.remove(条件)
示例:
db.book.save({'name':'spring boot',type:'spring boot'}) //添加
db.book.remove({type:'spring boot'}) //删除
//修改第一条
db.book.update({name:'spring boot'}, {$set:{name:'Spring Boot'}})
//修改所有
db.book.updateMany({name:'spring boot'}, {$set:{type:'spring'}})
db.getCollection('book').find({}) //查询
db.book.find({type:'spring boot'}) //查询
Spring Boot 整合MongoDB(mongoTemplate增删改查)
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
添加配置项
spring:
data:
mongodb:
uri: mongodb://localhost/test
查询
@Test
void getTest() {
//查询全部
List<Book> all = mongoTemplate.findAll(Book.class);
System.out.println(all);
//根据id查询
Book book = mongoTemplate.findById("1", Book.class);
System.out.println(book);
//根据条件查询
Query query = new Query(Criteria.where("name").is("java"));
List<Book> list2 = mongoTemplate.find(query, Book.class);
System.out.println(list2);
//查询并排序
Query query2 = new Query().with(Sort.by(Sort.Direction.ASC,"name"));
List<Book> list3 = mongoTemplate.find(query2,Book.class);
System.out.println(list3);
//分页查询
Pageable pageable = (Pageable) PageRequest.of(0,4,Sort.by(Sort.Order.desc("id")));
Query query1 =new Query().with(pageable);
List<Book> list4 = mongoTemplate.find(query1, Book.class);
System.out.println(list4);
//查询数量
long count = mongoTemplate.count(new Query(Criteria.where("author").is("asd")), Book.class);
System.out.println("author 为asd的数量:"+count);
}
添加
@Autowired
MongoTemplate mongoTemplate;
@Test
void insert() {
Book book1 = new Book("1", "CSS", "asd");
Book book2 = new Book("2", "java", "asiudh");
Book book3 = new Book("3", "C#", "aasdou");
Book book4 = new Book("4", "javaSE", "jhgas");
mongoTemplate.insert(book1);
mongoTemplate.insert(book2);
mongoTemplate.insert(book3);
mongoTemplate.insert(book4);
}
更新
@Test
void upd(){
Query query = Query.query(Criteria.where("_id").is("4"));
Update update = Update.update("name","javaEE");
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Book.class);
System.out.println(updateResult);
}
删除
@Test
void del(){
Book book = new Book();
book.setId("111");
mongoTemplate.remove(book);
}
使用MongoRepository
使用MongoRepository实现评论管理
编写实体类:
package com.example.demo_mongodb.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
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;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "comment") //若省略,则默认使用类名小写映射集合
//@CompoundIndex(def = "{'userid':1,'nickname':-1}") //复合索引
public class Comment implements Serializable {
//主键标识 该属性的值会自动对应mongodb的主键字段 “_id”,若该属性名就叫“id”,则该注解可以省略,否则必须写
@Id
private String id; //主键
@Field("content") //对应mongodb字段的名字,若一致,则可以不写
private String content;
private Date publishtime; //发布日期
@Indexed
private String userid; //发布人id
private String nickname; //昵称
private LocalDateTime createtime;//评论日期时间
private Integer likenum; //点赞数
private Integer replynum; //回复数
private String state; //状态
private String parentid; //上级ID
private String articleid;
}
Dao层:
package com.example.demo_mongodb.dao;
import com.example.demo_mongodb.po.Comment;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CommentRepository extends MongoRepository<Comment,String> {
}
Servie层:
package com.example.demo_mongodb.service;
import com.example.demo_mongodb.dao.CommentRepository;
import com.example.demo_mongodb.po.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CommentService {
@Autowired
CommentRepository commentRepository;
public void saveComment(Comment comment){
commentRepository.save(comment);
}
public void updateComment(Comment comment){
commentRepository.save(comment);
}
public void deleteComment(String id){
commentRepository.deleteById(id);
}
/**
* 查询所有评论
* @return {@link List}<{@link Comment}>
*/
public List<Comment> findCommentList(){
return commentRepository.findAll();
}
/**
* 通过id查找评论
* @param id id
* @return {@link Comment}
*/
public Comment findCommentById(String id){
return commentRepository.findById(id).get();
}
}
测试:
package com.example.demo_mongodb;
import com.example.demo_mongodb.po.Comment;
import com.example.demo_mongodb.service.CommentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@SpringBootTest
public class CommentServiceTest {
@Autowired
CommentService commentService;
@Test
void testSave(){
Comment c = new Comment("2","写的太棒了", new Date(),"1004","汪汪汪",LocalDateTime.now(),0,0,"1","1","1");
commentService.saveComment(c);
}
@Test
void testFindAll(){
List<Comment> commentList = commentService.findCommentList();
commentList.forEach(comment -> {
System.out.println(comment);
});
}
@Test
void testUpdate(){
Comment c = new Comment("2","写的太棒了", new Date(),"1004","酷酷酷",LocalDateTime.now(),0,0,"1","1","1");
commentService.updateComment(c);
}
@Test
void testDelete(){
commentService.deleteComment("2");
}
}