- 配置数据源
spring:
data:
mongodb:
collection: msgDetails
uri: mongodb://tester01:tester01@127.0.0.1:27016/test
- pom 添加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- 注入工具类
@Autowired
private MongoTemplate mongoTemplate;
- 增删改查
Test
public void saveTest() {
mongoTemplate.save(person);
}
@Test
public void findTest() {
Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
System.out.println(p);
}
@Test
public void updateTest() {
mongoTemplate.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
System.out.println(p);
}
@Test
public void removeTest() {
List<Person> people = mongoTemplate.findAll(Person.class);
System.out.println(people.size());
Person p = mongoTemplate.findOne(query(where("name").is("Joe")), Person.class);
mongoTemplate.remove(p);
people = mongoTemplate.findAll(Person.class);
System.out.println(people.size());
mongoTemplate.dropCollection(Person.class);
}