SpringBoot集成MongoDB

SpringBoot集成MongoDB,第1张

官方文档https://www.mongodb.com/docs/manual/reference/method/
MongoDB介绍https://blog.csdn.net/weixin_44463473/article/details/124333852
MongoDB命令行使用https://blog.csdn.net/weixin_44463473/article/details/124334979
SpringBoot集成MongoDBhttps://blog.csdn.net/weixin_44463473/article/details/124372678
MongoDB副本集和分片集群https://blog.csdn.net/weixin_44463473/article/details/124366520

相关注解

@Document

​ 修饰范围:用在类上 作用:用来映射这个类的一个对象为mongo中一条文档数据。

​ 属性:( value . collection )用来指定 *** 作的集合名称

@Id

​ 修饰范围:用在成员变量、方法上

​ 作用:用来将成员变量的值映射为文档的_id的值.

@Field

​ 修饰范围:用在成员变量、方法上

​ 作用:用来将成员变量以及值映射为文档中一个key、value对

​ 属性:( name , value )用来指定在文档中key的名称,默认为成员变量名

@Transient

​ 修饰范围:用在成员变量、方法上

​ 作用:用来指定改成员变量,不参与文档的序列化
整合应用

​ 说明:这里主要以springboot应用为基础应用进行整合开发。Spring Data : Spring 数据框架JPA , Redis、Elasticsearch、AMQP、MongoDBJdbcTemplate、RedisTemplate、ElasticTempalte、MongoTemplate

启动mongod:systemctl start mongod


   org.springframework.boot
   spring-boot-starter-data-mongodb

#mongodb(协议)://主机:端口/库名
spring.data.mongodb.uri=mongodb://124.222.89.10:27017/baizhi

entity类

@Data
@Document("users")
public class User {
    @Id
    private Integer id;
    @Field
    private String name;
    @Field
    private Double salary;
    @Field
    private Date birthday;
}

test测试

@SpringBootTest
public class MongoTemplateTests{
     private static MongoTemplate mongoTemplate;

     @Autowired
    public MongoTemplateTests(MongoTemplate mongoTemplate){
         this.mongoTemplate =mongoTemplate;
     }

     //创建集合
     @Test
    public void testCreateCollection(){
         mongoTemplate.createCollection("products");
     }


     //删除集合
     @Test
     public void deleteCollectionByName(){
         String collectionName = "users";
         mongoTemplate.dropCollection(collectionName);
     }

     //插入文档
     @Test
    public void testInsert(){
         User user = new User();
         user.setId(2);
         user.setName("chenke");
         user.setSalary(2.2);
         user.setBirthday(new Date());
         User save = mongoTemplate.save(user);
         System.out.println(save);
     }

     //删除所有文档
     @Test
    public void deleteAllUser(){
         DeleteResult remove = mongoTemplate.remove(new Query(), User.class);
     }

     //条件删除
    @Test
    public void deleteUserByQuery(){
        //条件删除
        DeleteResult deleteResult = mongoTemplate.remove(Query.query(Criteria.where("name").is("xinan")), User.class);
    }

    //1、更新符合条件的第一条数据
    @Test void updateFirst(){
        Update update = new Update();
        update.set("salary",444.4);
        mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("chenke")),update,User.class);
        List<User> user = mongoTemplate.find(Query.query(Criteria.where("name").is("chenke")),User.class);
        System.out.println(user);
    }

    //2、更新符合条件的所有数据
    @Test
    public void updateMulti(){
        Update update = new Update();
        update.set("salary",333.4);
        mongoTemplate.updateMulti(Query.query(Criteria.where("name").is("chenke2")),update,User.class);
        List<User> users = mongoTemplate.find(Query.query(Criteria.where("name").is("chenke2")),User.class);
       users.forEach(System.out::println);
    }

    //3、更新符合条件的第一条数据,没有符合条件的将插入
    @Test
    public void upsert(){
        Update update = new Update();
        update.setOnInsert("id",13);
        update.setOnInsert("name","chenke4");
        update.set("salary",42222.4);
        update.setOnInsert("birthday",new Date());
        UpdateResult updateResult = mongoTemplate.upsert(Query.query(Criteria.where("name").is("chenke4")), update, User.class);
        List<User> users = mongoTemplate.find(Query.query(Criteria.where("name").is("chenke3")),User.class);
        users.forEach(System.out::println);
    }

    //1、查询所有
    @Test
    public void findAllUser(){
        List<User> user = mongoTemplate.findAll(User.class);
        user.forEach(System.out::println);
    }

    //根据id查询
    @Test
    public void findUserById(
    ){
         Scanner scanner = new Scanner(System.in);
         Integer id = scanner.nextInt();
        User user = mongoTemplate.findById(id, User.class);
        System.out.println(user);
    }

    @Test
    public void findUserByQuery(){
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        Query query = Query.query(Criteria.where("name").is(userName));
        List<User> users = mongoTemplate.find(query, User.class);
        users.forEach(System.out::println);
    }

    //and
    @Test
    public void findUserByQueryAnd(){
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        Query queryAnd = Query.query(Criteria.where("name").is(userName).and("id").is(0));
        List<User> users = mongoTemplate.find(queryAnd, User.class);
        users.forEach(System.out::println);
    }

    //or
    @Test
    public void findUserByQueryOr(){
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        Query queryAnd = Query.query(Criteria.where("name").is(userName).and("id").is(0));
        List<User> users = mongoTemplate.find(queryAnd, User.class);
        users.forEach(System.out::println);
    }

    //or and
    @Test
    public void findUserByQueryOrAnd(){
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        //and or
        Criteria criteriaAndOr = new Criteria();
        criteriaAndOr.and("age").is(0)
                .orOperator(
                        Criteria.where("name").is(userName),
                        Criteria.where("name").is(userName)
                );
         List<User> users = mongoTemplate.find(Query.query(criteriaAndOr), User.class);
        users.forEach(System.out::println);
    }

    //Sort
    @Test
    public void findUserByQuerySort(){
        Query querySort = new Query();
        querySort.with(Sort.by(Sort.Order.desc("salary")));
        List<User> users =  mongoTemplate.find(querySort,User.class);
        users.forEach(System.out::println);
    }


    //limit
    @Test
    public void findUserByQueryLimit(){
        Query queryLimit = new Query();
        queryLimit.with(Sort.by(Sort.Order.desc("salary"))).skip(0).limit(2);
        List<User> userLimit =  mongoTemplate.find(queryLimit,User.class);
        userLimit.forEach(System.out::println);
    }

    //count
    @Test
    public void findUserCount(){
        //总条数
         long count = mongoTemplate.count(new Query(), User.class);
        System.out.println(count);
    }

    //distinct
    @Test void findUserDistinct(){
        //去重
        List<Double> salary = mongoTemplate.findDistinct(new Query(), "salary", User.class, Double.class);
    }

    //basicQuery JOSN
    @Test
    public void basicQuery(){
        BasicQuery basicQuery = new BasicQuery("{name:'string'}");
        List<User> users = mongoTemplate.find(basicQuery, User.class);
        users.forEach(System.out::println);
    }
}

如果是配置副本集

spring.data.mongodb.uri=mongodb://124.222.89.10:27017,124.222.89.10:27018,124.222.89.10:27019/chenke?replicaSet=myreplace

如果使用swagger-ui测试

整合swagger

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2).select().
                apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    }
}

集合管理:CollectionController

@RestController
@RequestMapping("/CollectionController")
@Api(tags = "集合管理")
public class CollectionController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/insertCollection")
    @ApiOperation(value = "insert",notes = "添加集合")
    public String insertCollectionByName(
            String collectionName
    ){
        boolean b = mongoTemplate.collectionExists(collectionName);
        if(!b){
            MongoCollection<Document> collection = mongoTemplate.createCollection(collectionName);
            return "创建成功";
        }else {
            return "集合已经存在";
        }
    }

    @DeleteMapping("deleteCollectionByName")
    @ApiOperation(value = "delete",notes = "删除集合")
    public String deleteCollectionByName(
            String collectionName
    ){
        mongoTemplate.dropCollection(collectionName);
        return "删除成功";
    }
}

测试:

http://localhost:8080/swagger-ui.html

需要代码请前往:https://gitee.com/crazy507/SpringBoot-MongoDB-gitee

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/731446.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存