The environment

  • MacOS
  • Mongo 5.0.2
  • Spring Boot 2.4.0

configuration

Create a Maven project, import the dependent JAR package, and configure POM.xml.

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> </parent> <dependencies> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> < the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.18.12 < / version > <scope>compile</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> The < version > 1.2.71 < / version > < / dependency > < / dependencies >Copy the code

Modify application.properties to the following:

Spring. The data. The mongo. Host = 127.0.0.1 spring. The data. The mongo. Port = 27017 # spring. Data. The mongo. Username = #spring.data.mongodb.password= spring.data.mongodb.database=userCopy the code

The project structure is:

Pom. XML └ ─ ─ the SRC ├ ─ ─ the main │ ├ ─ ─ Java │ │ └ ─ ─ cn │ │ └ ─ ─ coder47 │ │ ├ ─ ─ Application. Java │ │ ├ ─ ─ model │ │ │ └ ─ ─ ├ ─ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java │ ├ ─ Java ├── ├─ Java ├─ ├─ Java ├─ JavaCopy the code

Model

@Data
public class User {

    private Integer id;

    private String username;

    private String phone;

    private String sex;

    private String nickname;

    private Date lastModified;
}
Copy the code

Repository

public interface UserRepository extends MongoRepository<User, Integer> {
}
Copy the code

Commonly used API

Spring Data mainly provides two classes and interfaces to manipulate MongDB, namely, MongoRepository and MongoTemplate. MongoRepository provides simple document CRUD interfaces, while MongoTemplate provides collection CRUD and document CRUD interfaces, as well as complex conditional query and aggregation analysis of documents.

MongoTemplate

@Slf4j @SpringBootTest public class MongoTemplateTest { @Autowired MongoTemplate mongoTemplate; private static final String COLLECTION_NAME = "user"; / * * * * / delete set @ Test public void dropCollection () {mongoTemplate. DropCollection (COLLECTION_NAME); */ @test public void getCollection() {Set<String> collectionNames = mongoTemplate.getCollectionNames(); log.info(JSON.toJSONString(collectionNames)); } / create the collection * * * * / @ Test public void createCollection () {Boolean exists. = mongoTemplate collectionExists (COLLECTION_NAME);  If (exists) {log.info(" set already exists "); return; } CollectionOptions CollectionOptions = collectionoptions.empty ().size(6142800) // Specify a maximum value for the fixed set, That is, the number of bytes.maxDocuments(10000) // Specifies the maximum number of documents to contain in a fixed collection. //.capped() creates a fixed set if it is true. A fixed collection is a collection of a fixed size that automatically overwrites the earliest documents when it reaches its maximum. .collation(Collation.of(Locale.CHINA.getLanguage())); / / custom Chinese collation mongoTemplate. CreateCollection (COLLECTION_NAME collectionOptions); } @test public void insert() {User User = new User(); user.setId(1); User. SetUsername (" zhang "); user.setPhone("131000281912"); User. SetNickname (" little three "); User. SetSex (" male "); user.setLastModified(new Date()); mongoTemplate.insert(user); User user1 = new User(); user1.setId(2); User1. SetUsername (" li si "); user1.setPhone("132000281912"); User1. SetNickname (" four "); User1. SetSex (" male "); user1.setLastModified(new Date()); mongoTemplate.insert(user1); } @test public void findAll() {List<User> all = mongotemplate.findall (user.class, COLLECTION_NAME); log.info(JSON.toJSONString(all)); Mongotemplate.findbyid (1, user.class, COLLECTION_NAME); / / @test public void findById() {mongotemplate.findbyid (1, user.class, COLLECTION_NAME); log.info(JSON.toJSONString(user)); } @test public void findByCondition() {Query Query = new Query(Criteria) Where (" phone "). The is (" 131000281912 "). And (" id "). Gte (1) and (" username ") in (" zhang ", "li si")); / / sorting query. With (Sort) by (Sort. Order. Asc (" username "))); Pageable Pageable = PageRequest. Of (0, 10); query.with(pageable); List<User> users = mongoTemplate.find(query, User.class, COLLECTION_NAME); long count = mongoTemplate.count(query, User.class); Page<User> page = PageableExecutionUtils.getPage(users, pageable, () -> count); log.info(JSON.toJSONString(page)); } @Test public void getCount() { Query query = new Query(Criteria .where("phone").is("131000281912") .and("id").gte(1) . And ("username").in(" username", "username")); long count = mongoTemplate.count(query, User.class, COLLECTION_NAME); log.info(JSON.toJSONString(count)); } /** * update the document */ @test public void update() {User User = new User(); user.setId(2); User. SetUsername (" li si "); user.setPhone("131000281922"); User. SetNickname (" four "); User. SetSex (" female "); user.setLastModified(new Date()); mongoTemplate.save(user, COLLECTION_NAME); Mongotemplate.remove (new Query(), user.class, COLLECTION_NAME); mongotemplate.remove (new Query(), user.class, COLLECTION_NAME); } / Aggregation * / * * * @ Test public void aggregate () {/ / count Aggregation countAggregation = Aggregation. NewAggregation ( count().as("count") ); AggregationResults countAggregate = mongoTemplate.aggregate(countAggregation, User.class, HashMap.class); log.info(JSON.toJSONString(countAggregate)); / / sum Aggregation sumAggregation = Aggregation. NewAggregation (match (Criteria. The where (" sex ") in (" male "and" female ")), group().max("id").as("sum") ); AggregationResults sumAggregate = mongoTemplate.aggregate(sumAggregation, User.class, HashMap.class); log.info(JSON.toJSONString(sumAggregate)); // max Aggregation maxAggregation = Aggregation.newAggregation( group().max("id").as("max") ); AggregationResults maxAggregate = mongoTemplate.aggregate(maxAggregation, User.class, HashMap.class); log.info(JSON.toJSONString(maxAggregate)); }}Copy the code

MongoRepository

@Slf4j @SpringBootTest public class MongoRepositoryTest { @Autowired UserRepository userRepository; / / @test public void insert() {User User = new User(); user.setId(1); User. SetUsername (" zhang "); user.setPhone("131000281912"); User. SetNickname (" little three "); user.setLastModified(new Date()); userRepository.insert(user); } @test public void findAll() {Sort Sort = sort.by (sort.order.asc ("id")); PageRequest pageRequest = PageRequest.of(0, 10, sort); Page<User> page = userRepository.findAll(pageRequest); log.info(JSON.toJSONString(page)); } @test public void count() {long count = userrepository.count (); log.info(JSON.toJSONString(count)); } /** * id */ @test public void findById() {User User = userrepository.findById (1).orelse (null); log.info(JSON.toJSONString(user)); } @test public void findByCondition() {User User = new User(); User. SetUsername (" zhang "); user.setPhone("131000281912"); ExampleMatcher matcher = ExampleMatcher.matching() .withIgnoreNullValues() .withIgnorePaths("id", "nickname", "lastModified") .withMatcher("username", ExampleMatcher.GenericPropertyMatcher::endsWith) .withMatcher("username", ExampleMatcher.GenericPropertyMatcher::startsWith); Example example = Example.of(user, matcher); List list = userRepository.findAll(example); log.info(JSON.toJSONString(list)); } /** * update the document */ @test public void update() {User User = new User(); user.setId(1); User. SetUsername (" zhang SAN 1 "); user.setPhone("131000281922"); User. SetNickname (" small three 1 "); user.setLastModified(new Date()); userRepository.save(user); } / delete documents * / * * * @ Test public void deleteById () {userRepository. DeleteById (1); }}Copy the code

conclusion

The above is the common API of Spring Data MongoDB, more usage can refer to: Spring Data MongoDB documentation.