Crud mongodb using mongotemplate

Manon up2u 2021-10-14 07:57:05
 Code the agriculture UP2U
Code the agriculture UP2U
About Java、PHP、 Other programming languages …… Or safety 、 Or yard farmers 、 Or technology 、 Or summarize ! Exchange of learning , Common progress ! Code the agriculture up to you, Code the agriculture UP2U!
139 Original content
official account

Early articles

        MongoDB Is a database based on distributed file storage , from C++ To write , It's a scalable high-performance data storage solution . Take a look at MongoDB Official website for MongoDB A brief introduction .


One 、MongoDB Brief introduction

        stay MongoDB in , Some of its nouns are different from those of relational database , I introduce a picture for your reference , As shown in the figure below .


The picture comes from the following website :

        stay MongoDB in , Set is equivalent to the concept of table in relational database , But it's different from a watch . Because different data can be stored under the same set , And there is no association relationship between sets . It also has no concept of columns , In the use of MongoDB There is no need to define its columns and data types in advance ( Although in actual use, it will be defined through entity classes ), There is no concept of columns , Then the data in each row can store completely different data , Such as product details , You can put mobile phones and computers into a collection , But the parameter details of mobile phone and computer are completely different , about MongoDB There is no problem in terms of .

        In the face of MongoDB After a brief introduction , Introduce a few more MongoDB Common commands :

1. see MongoDB Database in

show dbs


2. Select database

use local


3. View collections in the database

show collections


4. View all data in the collection


        Use more commands , You can refer to MongoDB Learn about .

Two 、 stay SpringBoot Introduce dependency in

        stay SpringBoot Project use MongoDB, The first thing we need to do is introduce MongoDB Dependence , By means of POM Introduce in the file MongoDB Dependent coordinates of , The operation can be MongoDB Class libraries are integrated into SpringBoot In the project , Related dependencies are as follows :

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>

3、 ... and 、 Add the configuration

         After introducing dependency , Need to add in profile MongoDB The address of , As we use MySQL Also need to give its address .

spring: data: mongodb: uri: mongodb://

        Above uri in ,test Designated us Demo Database to be operated in .

Four 、 Define correspondence MongoDB The entity class of the set in

        operation MySQL when , We will MySQL The table defines a corresponding entity class in the project , operation MongoDB The collection also needs to define a corresponding entity class . So let's define a Student Entity class as Demo To operate on entity classes in .

@Data@Document("Student")public class Student {
@Id private String id; private String name; private Integer age; private String email;}

        Add comments to the entity class @Document,@Document Given in is the name of the set . annotation @Id This field will be associated with MongoDB Generated _id Association .

        In the specific operation MongoDB You can go through MongoTemplate To operate , It can also be done through MongoRepository To operate . Now we'll show you how to use MongoTemplate To finish. MongoDB Of CRUD operation .

5、 ... and 、 Use  MongoTemplate complete CRUD

        MongoTemplate be based on Spring The container provides a set of pairs MongoDB The basic method of operation , As long as MongoTemplate Inject into the class you need to use , It can be used directly .

1. Inject MongoTemplate

        Create a test class , adopt @Autowired take MongoTemplate For injection , The code is as follows .

@Autowiredprivate MongoTemplate mongoTemplate;

2. Add operation

        At injection MongoTemplate after , We can do it in the test class CRUD The operation of , First, complete an operation to add data , The code is as follows :

/** * Add operation  */@Testvoid create() { for (int i = 0; i < 10; i ++) { Student student = new Student(); student.setAge(20 + i); student.setName("test" + i); student.setEmail(i + "");
Student insert = mongoTemplate.insert(student);
System.out.println(insert); }}

        adopt MongoTemplate Of insert Method , You can complete the data insertion operation .

        After executing the above test code , We go through MongoDB To view the data we added . First, through show dbs Order to see MongoDB Database in , You can see one more test database , As shown in the figure below :


        then , Use use Select the database , Use show collections see test Set under , You can see in the test A... Is automatically created under the database Student Set , As shown in the figure below :


        You can see , Before we execute the above method , Didn't create test database , No creation Student aggregate . After executing the above code , Automatically created test Database and Student aggregate , And in Student Inserted... In the collection 10 Documents .

3. Query all records in the collection

        The above completes the operation of inserting document data , Now through MongoTemplate To find out all of it , The code is as follows :

/** * Query all records in the table  */@Testvoid findAll() { List<Student> all = mongoTemplate.findAll(Student.class);

        adopt MongoTemplate Of findAll Method can query all documents under the specified collection .

        After executing the above code , The console will output Student All documents in the collection , The output is as follows .

Student(id=614c43b77fbbb70ee5016e52, name=test0, age=20,, name=test1, age=21,, name=test2, age=22,, name=test3, age=23,, name=test4, age=24,, name=test5, age=25,, name=test6, age=26,, name=test7, age=27,, name=test8, age=28,, name=test9, age=29,

         As you can see from the output ,MongoDB Generated for us id, Through this id We can uniquely identify a piece of data .

4. adopt id Query the specified document

        Usually , When we query a specified piece of data, we will pass id The query , When adding data , You can see MongoDB For us to automatically generate id, be known as _id, As long as through the MongoTemplate Of findById Method , And pass in the corresponding id Value to query , The code is as follows :

/** * according to id Inquire about  */@Testvoid findById() { Student byId = mongoTemplate.findById("614c43b77fbbb70ee5016e52", Student.class);

        As you can see from the above code , adopt MongoTemplate Of findById You can get the specified id Documents .

5. Conditions of the query

        MongoDB Support very powerful query function , Here we simply complete a conditional query . The code is as follows :

/** * Conditions of the query  */@Testvoid findUserList() { // name = test0 and age = 20 Query query = new Query( Criteria.where("name").is("test0") .and("age").is(20) );
List<Student> users = mongoTemplate.find(query, Student.class);

        In the code above ,Criteria yes MongoTemplate Standard query interface , It can splice multiple query conditions through chain operation , And then through Query You can build query statements , The above query is equivalent to the following SQL sentence :

select * from student where name = 'test0' and age = 20

        Finish another or Query for , The code is as follows :

/** * Conditions of the query  */@Testvoid findUserList() { Query query = new Query( new Criteria().orOperator( Criteria.where("name").is("test0").and("age").is(20), Criteria.where("age").gt(25) ) );
List<Student> users = mongoTemplate.find(query, Student.class);

        Notice the code above about Criteria Writing , The above code , Equivalent to SQL sentence :

select * from student where (name = 'test0' and age = 20) or (age > 25)

        or The output of the query is as follows :

Student(id=614c43b77fbbb70ee5016e52, name=test0, age=20,, name=test6, age=26,, name=test7, age=27,, name=test8, age=28,, name=test9, age=29,

        From the above output, you can verify or The query is written correctly .

6. Fuzzy query

        MongoDB Fuzzy queries can be done using regular expressions , The code is as follows :

/** * Fuzzy query  */@Testvoid findLikeUserList() { // name like test and age = 20
String name = "est"; String regex = String.format("%s%s%s", "^.*", name, ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = new Query( Criteria.where("name").regex(pattern) .and("age").is(20) );
List<Student> users = mongoTemplate.find(query, Student.class);

        In the above code , stay Criteria.where I used regex, instead of is, You can use regular expressions to query . The fuzzy query above is equivalent to SQL Statement like, Because of our name Fields can match est character string , This example doesn't make much sense .

7. Paging query

        stay MySQL Paging query of data in , Generally, the page number and the number of records per page need to be passed into the interface , Of course, you also need to pass in some query criteria . about MongoDB for , The same is true for the data passed into the interface .

/** * Paging query  */@Testvoid findPageUserList() { int pageNo = 2; int pageSize = 3;
    //  Conditional component Query query = new Query( Criteria.where("age").gt(23) );
// Paging component // Number of query records long count = mongoTemplate.count(query, Student.class); // Pagination List<Student> users = mongoTemplate.find( query.skip((pageNo - 1) * pageSize) .limit(pageSize), Student.class);
System.out.println(count); users.forEach(System.out::println);}

         Paging query passed query Of skip and limit To complete , This is also similar to MySQL Of limit Usage of . In the above code , Our pagination is displayed per page 3 strip , The current page is page 2 page . In the code 16 That's ok , adopt MongoTemplate Of count Get the total number of records that meet the conditions , The data output from the above code is as follows :

6Student(id=614c43b77fbbb70ee5016e59, name=test7, age=27,, name=test8, age=28,, name=test9, age=29,

         In our terms , Let's check age Greater than 23 Of , That is from 24 To 29, Altogether 6 Data . front 3 The bar is 24 To 26, Then the data here is correct .

8. Modifying data

        When modifying data, first query the data , Then set the value to be modified , Update the data .

/** * modify  */@Testvoid updateUser() { // according to id Inquire about  Student user = mongoTemplate.findById("614c43b77fbbb70ee5016e59", Student.class);
// Set the modified value assert user != null; user.setName("zhangsan"); user.setAge(30); user.setEmail("");
Query query = new Query(Criteria.where("_id").is(user.getId())); Update update = new Update(); update.set("name", user.getName()); update.set("age", user.getAge()); update.set("email", user.getEmail());
// Call the method to implement the modification UpdateResult upsert = mongoTemplate.upsert(query, update, Student.class);

        adopt MongoTemplate Of upsert Method can modify the data , The modified data is shown in the figure below :


        In the code above , If you only need to update name or age or email One of them , Then you only need to set one of the values , You don't need to do it all set.

9. Delete data

        The deletion operation is also through Query Class constructs the condition to delete , And then call remove Method to delete .

/** * Delete operation  */@Testvoid deleteUser(){ Query query = new Query(Criteria.where("_id").is("614c43b77fbbb70ee5016e59"));
DeleteResult remove = mongoTemplate.remove(query, Student.class);

        adopt MongoTemplate Of remove Method , We deleted a piece of data , adopt db.Student.find() Command to view , You can see the updated zhangsan That data has been deleted . call remove After the method , Returns the DeleteResult object , Call... Through this object getDeletedCount Method to get the number of records deleted .

6、 ... and 、 summary

        MongoDB It has been used more and more , It is suitable for a large number of 、 Data without fixed data structure is stored . This article briefly introduces how to use MongoTemplate Come on MongoDB Conduct CRUD The operation of . Let's introduce it next time MongoRepository Yes MongoDB Of CRUD operation .

More articles


Please bring the original link to reprint ,thank
Similar articles