入门案例
- 创建工程,导入依赖
导入依赖
点击查看代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
点击查看代码
spring:
data:
mongodb:
uri: mongodb://192.168.200.130:27017/集合名
点击查看代码
@SpringBootApplication
public class MongoApplication {
public static void main(String[] args) {
SpringApplication.run(MongoApplication.class, args);
}
}
点击查看代码
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(value="user")
public class Person {
@Id
private ObjectId id;
@Field("username")
private String name;
private int age;
private String address;
}
- 通过MongoTemplate完成CRUD操作
注入MongoTemplate对象
点击查看代码
@Autowired
private MongoTemplate mongoTemplate;
保存
点击查看代码
@Test
public void testSave() {
for (int i = 0; i < 10; i++) {
Person person = new Person();
person.setId(ObjectId.get()); //ObjectId.get():获取一个唯一主键字符串
person.setName("张三"+i);
person.setAddress("北京顺义"+i);
person.setAge(18+i);
mongoTemplate.save(person);
}
}
查询-查询所有
点击查看代码
@Test
public void testFindAll() {
List<Person> list = mongoTemplate.findAll(Person.class);
for (Person person : list) {
System.out.println(person);
}
}
查询条件对象
点击查看代码
@Test
public void testFind() {
//查询年龄小于20的所有人
Query query = new Query(Criteria.where("age").lt(20)); //查询条件对象
//查询
List<Person> list = mongoTemplate.find(query, Person.class);
for (Person person : list) {
System.out.println(person);
}
}
分页查询
点击查看代码
@Test
public void testPage() {
Criteria criteria = Criteria.where("age").lt(30);
//1 查询总数
Query queryCount = new Query(criteria);
long count = mongoTemplate.count(queryCount, Person.class);
System.out.println(count);
//2 查询当前页的数据列表, 查询第二页,每页查询2条
Query queryLimit = new Query(criteria)
.limit(2)//设置每页查询条数
.skip(2) ; //开启查询的条数 (page-1)*size
List<Person> list = mongoTemplate.find(queryLimit, Person.class);
for (Person person : list) {
System.out.println(person);
}
}
更新,根据id,更新年龄
点击查看代码
@Test
public void testUpdate() {
//1 条件
Query query = Query.query(Criteria.where("id").is("5fe404c26a787e3b50d8d5ad"));
//2 更新的数据
Update update = new Update();
update.set("age", 20);
mongoTemplate.updateFirst(query, update, Person.class);
}
根据id删除
点击查看代码
@Test
public void testRemove() {
Query query = Query.query(Criteria.where("id").is("5fe404c26a787e3b50d8d5ad"));
mongoTemplate.remove(query, Person.class);
}