1 引用依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2 配置文件配置mongodb资料
# MongoDB连接信息
spring.data.mongodb.host = 192.168.23.27
spring.data.mongodb.port = 27017
spring.data.mongodb.database = mallspring.data.mongodb.auto-index-creation = true
3 准备对象Person
/*
* Copyright (c) 2020, 2024, All rights reserved.
*
*/
package com.by.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.lang.annotation.Documented;
import java.time.LocalDateTime;
import java.util.Date;
/**
* <p>Project: SpringBoot_MongoDb - Person</p>
* <p>Powered by scl On 2024-04-12 14:14:01</p>
* <p>描述:<p>
*
* @author 孙臣龙 [1846080280@qq.com]
* @version 1.0
* @since 17
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "person") //如果要设置过期时间,需要设置collection
public class Person {
private Integer id ;
private String name ;
private Integer age ;
//设置过期时间
//@Indexed(expireAfterSeconds = 5)
//private LocalDateTime createTime ;
}
4、新增文档
package com.by;
import com.by.model.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@SpringBootTest
class AddTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 默认集合插入
*/
@Test
void test1() {
Person person = Person.builder().id(1).name("章五郎").age(28).build();
Person insert = mongoTemplate.insert(person);
System.out.println(insert);
}
/**
* 指定集合插入
*/
@Test
void test2() {
Person person = Person.builder().id(1).name("章五郎").age(28).build();
Person insert = mongoTemplate.insert(person, "my_person");
System.out.println(insert);
}
/**
* 批量插入
*/
@Test
void test3() {
List<Person> list = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
Person person = Person.builder().id(i).name("章五郎" + i).age(i + 20).build();
list.add(person);
}
Collection<Person> people = mongoTemplate.insertAll(list);
System.out.println(people);
}
/**
* 判断数据库中是否存在,如果不存在就插入,如果存在就更新
*/
@Test
void test4() {
Person person = Person.builder().id(1).name("大帅").age(20).build();
Person save = mongoTemplate.save(person);
System.out.println(save);
}
/**
* 过期设置
*/
@Test
void test5() {
//Person person = Person.builder().id(11).name("大帅").age(28).createTime(LocalDateTime.now()).build();
//Person save = mongoTemplate.insert(person);
//System.out.println(save);
}
}
5、删除文档
package com.by;
import com.by.model.Person;
import com.mongodb.client.result.DeleteResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;
@SpringBootTest
class DeleteTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 删除符合条件的所有文档
*/
@Test
void test1() {
Query query = new Query(Criteria.where("age").gt(10));
DeleteResult remove = mongoTemplate.remove(query, Person.class);
long deletedCount = remove.getDeletedCount();
System.out.println(deletedCount);
}
/**
* 删除符合条件的单个文档,并返回删除的文档
*/
@Test
void test2() {
Query query = new Query(Criteria.where("name").is("章五郎2"));
Person result = mongoTemplate.findAndRemove(query, Person.class);
System.out.println("删除的内容为:"+result);
}
/**
* 删除符合条件的所有文档,并返回删除的文档
*/
@Test
void test3() {
Query query = new Query(Criteria.where("age").lte(30));
List<Person> list=mongoTemplate.findAllAndRemove(query, Person.class);
for (Person person :list){
System.out.println("删除的内容为:" + person);
}
}
}
6、查询文档
package com.by;
import com.by.model.Person;
import com.mongodb.client.result.DeleteResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
class SelectTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 查询集合中的全部文档数据
*/
@Test
void test1() {
List<Person> list = mongoTemplate.findAll(Person.class);
for (Person person : list) {
System.out.println(person);
}
}
/**
* 查询集合中指定的ID文档数据
*/
@Test
void test2() {
Person person = mongoTemplate.findById(1, Person.class);
System.out.println(person);
}
/**
* 根据条件查询集合中符合条件的文档,返回第一条数据
*/
@Test
void test3() {
Query query = new Query(Criteria.where("age").gt(18));
Person one = mongoTemplate.findOne(query, Person.class);
System.out.println(one);
}
/**
* 根据【AND】关联多个查询条件,查询集合中所有符合条件的文档数据
*/
@Test
void test4() {
Query query = new Query();
Criteria age = Criteria.where("age").is(18);
Criteria name = Criteria.where("name").is("章五郎1");
Criteria criteria = new Criteria().andOperator(age, name);
query.addCriteria(criteria);
List<Person> list = mongoTemplate.find(query, Person.class);
for (Person person : list) {
System.out.println(person);
}
}
/**
* 根据【OR】关联多个查询条件,查询集合中所有符合条件的文档数据
*/
@Test
void test5() {
Query query = new Query();
Criteria age = Criteria.where("age").is(18);
Criteria name = Criteria.where("name").is("章五郎1");
Criteria criteria = new Criteria().orOperator(age, name);
query.addCriteria(criteria);
List<Person> list = mongoTemplate.find(query, Person.class);
for (Person person : list) {
System.out.println(person);
}
}
/**
* 根据【IN】关联多个查询条件,查询集合中所有符合条件的文档数据
*/
@Test
void test6() {
Query query = new Query();
List<Integer> list = new ArrayList<>();
list.add(18);
list.add(29);
list.add(30);
Criteria criteria = Criteria.where("age").in(list);
query.addCriteria(criteria);
List<Person> list1 = mongoTemplate.find(query, Person.class);
for (Person person : list1) {
System.out.println(person);
}
}
/**
* 根据【逻辑运算符】查询集合中的文档数据
*/
@Test
void test7() {
Query query = new Query();
Criteria criteria = Criteria.where("age").gte(18).lte(30);
//排序
query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC, "age"));
List<Person> list1 = mongoTemplate.find(query, Person.class);
for (Person person : list1) {
System.out.println(person);
}
}
/**
* 正则表达式
*/
@Test
void test8() {
Query query = new Query();
Criteria criteria = Criteria.where("name").regex("^章");
//排序 + 分页 + 限制条数
query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC, "age")).limit(2).skip(3);
List<Person> list1 = mongoTemplate.find(query, Person.class);
for (Person person : list1) {
System.out.println(person);
}
}
}
7、修改文档
package com.by;
import com.by.model.Person;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@SpringBootTest
class UpdateTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 根据条件修改
*/
@Test
void test1() {
//Query query, UpdateDefinition update, Class<?> entityClass
Query query = new Query();
// Criteria implements CriteriaDefinition
query.addCriteria(Criteria.where("name").is("大帅"));
//Update implements UpdateDefinition
Update update = new Update();
update.set("age", 18);
mongoTemplate.updateFirst(query,update , Person.class);
}
/**
* 根据多个条件修改
*/
@Test
void test3() {
//Query query, UpdateDefinition update, Class<?> entityClass
Query query = new Query();
// Criteria implements CriteriaDefinition
query.addCriteria(Criteria.where("name").is("大帅").and("age").is(18));
//Update implements UpdateDefinition
Update update = new Update();
update.set("age", 28);
UpdateResult result = mongoTemplate.updateFirst(query, update, Person.class);
System.out.println(result.getModifiedCount());
}
/**
* 根据条件修改全部的值
*/
@Test
void test2() {
//Query query, UpdateDefinition update, Class<?> entityClass
Query query = new Query();
// Criteria implements CriteriaDefinition
query.addCriteria(Criteria.where("age").gte(18));
//Update implements UpdateDefinition
Update update = new Update();
update.set("age", 18);
mongoTemplate.updateMulti(query,update , Person.class);
}
}
8、索引的使用
package com.by;
import com.by.model.Person;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.Indexed;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
@SpringBootTest
class IndexTest {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 创建升序索引
*/
@Test
void test1() {
String index = mongoTemplate.getCollection("person").createIndex(Indexes.descending("age"));
System.out.println(index);
}
/**
* 删除索引
*/
@Test
void test2() {
mongoTemplate.getCollection("person").dropIndex("age_-1");
}
/**
* 查询集合中所有的索引
*/
@Test
void test3() {
ListIndexesIterable<Document> person = mongoTemplate.getCollection("person").listIndexes();
for (Document document : person) {
System.out.println(document);
}
}
}