java集成mongodb,mongodbTemplate的使用

1.安装mongodb

        Ubuntu安装mongodb

        Ubuntu22.04安装MongoDB_城北徐公plus的博客-CSDN博客

        docker run mongodb

        待做

        window安装mongodb

        官网下载msi一直点击下一步即可:Download MongoDB Community Server | MongoDB

2.引入依赖

#已经版本控制,具体版本自己改
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

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

3.yml配置

spring:
  data:
    mongodb:
      host: xx.xx.xx.xx               #ip
      port: xx                        #端口
      database: myDb                  #要连接的数据库
      authenticationDatabase: admin   #身份验证指定的数据库
      username: xxx                   #账号
      password: xxx                   #密码

4.实体类

#实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId;

import java.io.Serializable;
import java.util.UUID;

@Data
@Document(collection = "human")
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Human implements Serializable {

    @MongoId
    private String id;

    private String name;
    private Integer age;
    private char sex;

    public Human(String name,Integer age,char sex){

        this.id = generateId();
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private String generateId(){

        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

5.集合操作样例

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.wgh.mongodb.pojo.Human;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/mongodb")
public class CollectionController {

    @Resource
    private MongoTemplate mongoTemplate;

    @PostMapping("/insert")
    public String insert(String tag){

        if ("1".equals(tag)){
            //添加单条数据,insert save
            Human hOne = mongoTemplate.insert(new Human("wgh",22,'男'), "human");
            System.out.println("hOne: " + hOne);

            Human save = mongoTemplate.save(new Human("wgh", 22, '男'), "human");
            System.out.println("save: " + save);
        }else {
            //添加多条数据
            Collection<Human> h_c = new ArrayList<>();
            h_c.add(new Human("hjx",22,'女'));
            h_c.add(new Human("yth",22,'女'));
            h_c.add(new Human("ysq",22,'女'));
            h_c.add(new Human("wdp",22,'女'));
            h_c.add(new Human("wj",22,'女'));
            Collection<Human> result = mongoTemplate.insertAll(h_c);
            result.forEach(h -> System.out.println(h));
        }
        return "redirect:/mongodb/collection";
    }

    @PostMapping("/delete")
    public String delete(String tag){

        Query query = Query.query(Criteria.where("name").is("wgh"));
        if ("1".equals(tag)){
            //删除符合条件的所有数据
            DeleteResult dr = mongoTemplate.remove(query, Human.class,"human");
            System.out.println(dr.getDeletedCount());
        }
        if ("2".equals(tag)){
            //删除符合条件的第一条数据,并返回被删除的数据
            Human human = mongoTemplate.findAndRemove(query, Human.class, "human");
            System.out.println(human);
        }
        if ("3".equals(tag)){
            //删除符合条件的所有数据,并返回被删除的数据
            List<Human> list = mongoTemplate.findAllAndRemove(query, Human.class, "human");
            list.forEach(h -> System.out.println(h));
        }
        return "redirect:/mongodb/collection";
    }

    @PostMapping("/update")
    public String update(String tag){

        Query query = Query.query(Criteria.where("name").is("wgh"));
        Update update = Update.update("age", 23);
        if ("1".equals(tag)){
            //无实际意义,不推荐使用
            mongoTemplate.update(Human.class);
        }
        if ("2".equals(tag)){
            //更新姓名为wgh的第一条数据
            UpdateResult human = mongoTemplate.updateFirst(query, update, Human.class, "human");
            System.out.println(human);
        }
        if ("3".equals(tag)){
            //更新姓名为wgh的所有数据
            UpdateResult human = mongoTemplate.updateMulti(query, update, Human.class, "human");
            System.out.println(human);
        }

        return "redirect:/mongodb/collection";
    }

    @PostMapping("/search")
    public String search(String tag){

        Query query = Query.query(Criteria.where("name").is("wgh"));
        if ("1".equals(tag)){
            //条件查询姓名为wgh的所有human
            List<Human> human = mongoTemplate.find(query, Human.class, "human");
            human.forEach(h -> System.out.println(h));
        }
        if ("2".equals(tag)){
            //条件查询姓名为wgh的第一条human
            Human human = mongoTemplate.findOne(query, Human.class, "human");
            System.out.println(human);
        }
        if ("3".equals(tag)){
            //查询所有human
            List<Human> human = mongoTemplate.findAll(Human.class, "human");
            human.forEach(h -> System.out.println(h));
        }
        if ("4".equals(tag)){
            //根据id查询
            Human byId = mongoTemplate.findById("c25a45d3f9104665b99f1514ce4d83a6", Human.class, "human");
            System.out.println(byId);
        }
        if ("5".equals(tag)){
            //条件查询性别为女的数据并根据姓名去重
            List<String> findDistinct = mongoTemplate
                    .findDistinct(new Query(Criteria.where("sex").is('女')), "name", "human", String.class);
            findDistinct.forEach(fd -> System.out.println(fd));
        }

        return "redirect:/mongodb/collection";
    }

    @PostMapping("/total")
    public String total(String tag){

        //删除集合
        if ("1".equals(tag)) mongoTemplate.dropCollection("human");
        //查找并修改姓名为wgh的第一条数据,并返回修改前的数据
        if ("2".equals(tag)){
            Human andModify = mongoTemplate.findAndModify(
                    Query.query(Criteria.where("name").is("wgh")),
                    Update.update("age", 100), Human.class,
                    "human"
            );
            System.out.println(andModify);
        }
        //统计姓名为wgh的数据条数
        if ("3".equals(tag)){
            long count = mongoTemplate.count(Query.query(Criteria.where("name").is("wgh")), Human.class);
            System.out.println("count: " + count);
        }
        return "redirect:/mongodb/collection";
    }

    @PostMapping("/aggregate")
    public String aggregate(String tag,String limit){

        if ("1".equals(tag)){
            //聚合查询name为wgh的数据,并将字段id,name,age,sex合为human的分组字段,通过年龄升序排列,每页限制limit条数据
            Aggregation agg = Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("name").is("wgh")), //条件
                    Aggregation.group("id","name","age","sex").count().as("human"), //分组字段
                    Aggregation.sort(Sort.Direction.ASC,"age"), //升序排序
                    Aggregation.limit(Long.parseLong(limit))  //每页显示数据条数
            );
            AggregationResults<String> human = mongoTemplate.aggregate(agg, "human",String.class);
            System.out.println("***************limit="+limit+"******************************");
            human.forEach(s -> System.out.println(s));
            System.out.println("*********************************************");
        }

        return "redirect:/mongodb/collection";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值