SpringBoot operation Mongodb

SpringBoot operation Mongodb

introduction

MongoDB Features

1. MongoDB is a document storage-oriented database, which is relatively simple and easy to operate.

2. You can set the index of any attribute in the MongoDB record (such as: FirstName="Sameer", Address="8 Gandhi Road") to achieve faster sorting.

3. You can create data mirroring locally or over the network, which makes MongoDB more scalable.

4. If the load increases (requires more storage space and stronger processing power), it can be distributed on other nodes in the computer network. This is called fragmentation.

5. Mongo supports rich query expressions. The query command uses JSON format tags, which can easily query the embedded objects and arrays in the document.

6. MongoDb can use the update() command to replace the completed document (data) or some specified data fields.

7. Map/reduce in Mongodb is mainly used for batch processing and aggregation operations on data.

8. Map and Reduce. The Map function calls emit(key, value) to traverse all the records in the collection, and passes the key and value to the Reduce function for processing.

9. The Map function and the Reduce function are written in Javascript, and the MapReduce operation can be executed through the db.runCommand or mapreduce command.

10. GridFS is a built-in function in MongoDB, which can be used to store a large number of small files.

11. MongoDB allows scripts to be executed on the server side. You can write a function in Javascript and execute it directly on the server side. You can also store the definition of the function on the server side and call it directly next time.

12. MongoDB supports various programming languages: RUBY, PYTHON, JAVA, C++, PHP, C# and other languages.

1. Initialize the project

Use Spring Initializr to quickly initialize a Spring Boot project

2. Dependency import


<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
 <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

It can also be said to import the mongodb dependency of SpringData

3. Add configuration

Add configuration to the application.properties file

spring.data.mongodb.uri=mongodb://192.168.10.41:27017/lps
#192.168.10.41为我的ip地址 27017为Mongodb端口号  lps是数据库 按需更改即可

4. Add entity class

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.util.Date;
/**
 * @Description
 * @Author 刘品水
 * @Data 2023/4/28 10:58
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document("users")//这个类的实例代表mongodb的一条文档 @AliasFor("collection")
public class User {
    
    
    @Id
    private Integer id;
    @Field("username")
    private String name;
    @Field
    private Double salary;
    @Field
    private Date birthday;
}

5. Operate Mongodb

automatic assembly

 @Autowired
    private MongoTemplate mongoTemplate;

create collection

@Test
void createCollection() {
    
    
    //判断是否存在
    boolean devIsExist = mongoTemplate.collectionExists("dev");
    if (!devIsExist) {
    
    
        //不存在就创建
        MongoCollection<Document> dev=mongoTemplate.createCollection("dev");
    }
}

delete collection

@Test
void testDropCollection() {
    
    
    //删除集合
    mongoTemplate.dropCollection("dev");
}

Test document addition function

   @Test
    void testDocAdd() {
    
    
        User user = new User(2, "彭于晏啊", 10086.00, new Date());
        //文档添加操作
        mongoTemplate.save(user); //save插入已存在的数据会进行更新
//        mongoTemplate.insert(user);//insert插入已存在的数据会DuplicateKeyException异常
    }

Test document batch add function

@Test
void testDocBatchAdd() {
    
    
    List<User> userList = new ArrayList<>();
    userList.add(new User(3, "吴彦祖", 10666.00, new Date()));
    userList.add(new User(4, "张无忌", 10886.00, new Date()));
    userList.add(new User(5, "盖伦", 50086.00, new Date()));
    //文档添加操作
    mongoTemplate.insert(userList, User.class);//参数:数据,元素类型
    //批量处理推荐insert
    //insert一次性可以插入整个数据  效果较高 save需要遍历整个数据,一次插入或更新 效果较低
}

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-MT1Rvm3a-1682671303029) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230428164128240.png)]

or, and content query function

  @Testj
    void testDocFind() {
    
    
        //文档查询操作()查询所有
        List<User> users = mongoTemplate.findAll(User.class);
//      users.forEach(System.out::println);
        //基于id查询一个
        User user = mongoTemplate.findById(1, User.class);
//        System.out.println(user);
        //条件Query查询全部
        List<User> users1 = mongoTemplate.find(new Query(), User.class);
        //条件Query查询
        List<User> users2 = mongoTemplate.find(Query.query(Criteria.where("name").is("刘品水")), User.class);
//        users2.forEach(System.out::println);//User(id=1, name=刘品水, salary=1000.0, birthday=Fri Apr 28 11:21:39 CST 2023)
        //条件 小于等于 大于等于  查询 less than equal | greater than equal
        List<User> users3 = mongoTemplate.find(Query.query(Criteria.where("salary").lte(10666)), User.class);
        List<User> users4 = mongoTemplate.find(Query.query(Criteria.where("salary").gte(10666)), User.class);

        //and 查询
        List<User> users5 = mongoTemplate.find(Query.query(Criteria.where("name").is("刘品水").and("salary").is(1000)), User.class);

        //or 查询
        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("name").is("刘品水"),
                Criteria.where("salary").is(10086)
        );
        List<User> users6 = mongoTemplate.find(Query.query(criteria), User.class);
        
        //or 和 and 查询
        List<User> users7 =mongoTemplate.find(Query.query(Criteria.where("name").is("刘品水")
                .orOperator(Criteria.where("salary").is(1000))), User.class);
        users7.forEach(System.out::println);
    }

Sorting, pagination, number of entries, deduplication query functions

 @Test
    void testDocFindByDifferent() {
    
    
        //排序
        Query querySort = new Query();
        querySort.with(Sort.by(Sort.Order.desc("salary")));
        List<User> users = mongoTemplate.find(querySort, User.class);

        //排序加分页
        Query querySortAndPage = new Query();
        querySortAndPage.with(Sort.by(Sort.Order.desc("salary")))
                .skip(3)
                .limit(3);
        List<User> users1 = mongoTemplate.find(querySortAndPage, User.class);
//        users1.forEach(System.out::println);

        //查询总条数
        long count = mongoTemplate.count(new Query(), User.class);
        System.out.println("总条数为"+count);
    }

Query using JSON format

   @Test
    void testDocFindByJSON() {
    
    
        //使用JSON字符串方式查询
        BasicQuery basicQuery = new BasicQuery("{name: '刘品水',salary: 66686}");
        BasicQuery basicQuery1 = new BasicQuery("{$or: [{name: '刘品水'},{salary: 50086}]}");
        BasicQuery basicQuery2 = new BasicQuery("{$or: [{name: '刘品水'},{salary: 50086}]}","{name: 1}");
        BasicQuery basicQuery3 = new BasicQuery("{$or: [{name: '刘品水'},{salary: 50086}]}","{salary: 0}");
        List<User> users = mongoTemplate.find(basicQuery3, User.class);
        users.forEach(System.out::println);
    }
  BasicQuery basicQuery3 = new BasicQuery("{$or: [{name: '刘品水'},{salary: 50086}]}","{salary: 0}");
        List<User> users = mongoTemplate.find(basicQuery3, User.class);
        users.forEach(System.out::println);
    }

Document update operation

 @Test
    void testUpdate() {
    
    
        //更新操作
        Update update = new Update();
        update.set("salary", 99999);
        //更新符合条件的第一条
//        mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("张无忌")), update, User.class);
        //更新符合条件的多条
        //mongoTemplate.updateMulti(Query.query(Criteria.where("name").is("张无忌")), update, User.class);
        //插入更新(没有符合条件的数据的时候插入数据)
        update.setOnInsert("id", 9);
        UpdateResult updateResult = mongoTemplate.upsert(Query.query(Criteria.where("name").is("迪迦奥特曼")), update, User.class);
        System.out.println("获取修改的计数"+updateResult.getModifiedCount());//获取修改的计数
        System.out.println("获取匹配计数"+updateResult.getMatchedCount());//获取匹配计数
        System.out.println("获取转换后的Id"+updateResult.getUpsertedId());//获取转换后的Id
    }

Document delete operation

  @Test
    //文档删除操作
    void testRemove() {
    
    
        //删除全部
//        mongoTemplate.remove(new Query(),User.class);
        //条件删除
        DeleteResult remove = mongoTemplate.remove(Query.query(Criteria.where("name").is("张无忌")), User.class);
        System.out.println("获取已删除计数"+remove.getDeletedCount());
        System.out.println(remove.wasAcknowledged());
    }
    }

Guess you like

Origin blog.csdn.net/lps12345666/article/details/130429592