mongodb springboot示例

学习网址1:https://www.runoob.com/mongodb/mongodb-intro.html

学习网址2:https://www.cnblogs.com/zhoujie/p/mongo1.html

  • pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.0.RELEASE
         
    
    com.zeng
    mongodb-demo
    0.0.1-SNAPSHOT
    mongodb-demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


  • dao接口

import com.zeng.entity.Persion;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface MongoDao extends MongoRepository {
}
  • application.yml

spring:
  data:
    mongodb:
      host: xxx.xxx.xxx.xxx
      database: xxx
      port: 27017
  • Service示例

import com.zeng.dao.MongoDao;
import com.zeng.entity.Persion;
import com.zeng.entity.SumEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MongoService {
    @Autowired
    private MongoDao mongoDao;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List list(){
        return mongoDao.findAll();
    }
    public void saveAll(List persions){
        mongoDao.saveAll(persions);
    }

    //查找各部门工资总和
    //db.mydb.aggregate([{$group:{_id:"$deptName",deptCount:{$sum:"$salary"}}}])
    public void sumSalaryByDept(){
        List operations=new ArrayList<>();

        AggregationOperation operation = Aggregation.group("deptName").sum("salary").as("sum");
        operations.add(operation);

        Aggregation aggregation=Aggregation.newAggregation(operations);

        AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, "mydb", SumEntity.class);

        Iterator iterator = aggregationResults.iterator();

        while (iterator.hasNext()){
            SumEntity sumEntity = iterator.next();
            System.out.println(sumEntity);
        }
    }

    //查找各部门指定入职时间段(309663802686332)员工的工资总和
    //db.mydb.aggregate([{$match:{hireTime:{$gte:309663832692998}}},{$group:{_id:"$deptName",salarySum:{$sum:"$salary"}}}])
    public void sumSalaryByDeptAndTime(){
        List operations=new ArrayList<>();

        Criteria criteria = Criteria.where("hireTime").gte(309663802686332l);
        MatchOperation matchOperation = Aggregation.match(criteria);
        operations.add(matchOperation);

        AggregationOperation operation = Aggregation.group("deptName").sum("salary").as("sum");
        operations.add(operation);

        Aggregation aggregation=Aggregation.newAggregation(operations);

        AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, "mydb", SumEntity.class);

        Iterator iterator = aggregationResults.iterator();

        while (iterator.hasNext()){
            SumEntity sumEntity = iterator.next();
            System.out.println(sumEntity);
        }
    }
    //查找各部门人数总和
    //db.mydb.aggregate([{$group:{_id:"$deptName",deptCount:{$sum:1}}}])
    public void countDept(){
        List operations=new ArrayList<>();
        AggregationOperation operation = Aggregation.group("deptName").count().as("sum");
        operations.add(operation);

        Aggregation aggregation=Aggregation.newAggregation(operations);

        AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, "mydb", SumEntity.class);

        Iterator iterator = aggregationResults.iterator();

        while (iterator.hasNext()){
            SumEntity sumEntity = iterator.next();
            System.out.println(sumEntity);
        }
    }
    //查找各部门指定入职时间段(309663802686332)员工的人数总和
    //db.mydb.aggregate([{$match:{hireTime:{$gte:309663832692998}}},{$group:{_id:"$deptName",salarySum:{$sum:"$salary"}}}])
    public void countDeptByDeptAndTime(){
        List operations=new ArrayList<>();

        Criteria criteria = Criteria.where("hireTime").gte(309663832692998L);
        MatchOperation matchOperation = Aggregation.match(criteria);
        operations.add(matchOperation);

        AggregationOperation operation = Aggregation.group("deptName").count().as("sum");
        operations.add(operation);

        Aggregation aggregation=Aggregation.newAggregation(operations);

        AggregationResults aggregationResults = mongoTemplate.aggregate(aggregation, "mydb", SumEntity.class);

        Iterator iterator = aggregationResults.iterator();

        while (iterator.hasNext()){
            SumEntity sumEntity = iterator.next();
            System.out.println(sumEntity);
        }
    }
}
  • 实体类

import lombok.Data;
import org.springframework.data.annotation.Id;

import java.math.BigDecimal;

@Data
public class SumEntity {
    @Id
    private String name;
    private BigDecimal sum;
}
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.util.Date;

@Document("mydb")
@Data
public class Persion implements Serializable {
    @Id
    private String id;
    private String name;
    private int age;
    private double salary;
    private long hireTime;
    private String deptName;
}
  • 测试类

import com.zeng.entity.Persion;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoServiceTest {
    @Autowired
    private MongoService mongoService;

    @Test
    public void testList() {
        long currentTimeMillis = System.currentTimeMillis();
        List list = mongoService.list();
        System.out.println(System.currentTimeMillis()-currentTimeMillis);
        System.out.println(list.size());
    }

    @Test
    public void testSaveAll() {
        String[] depts={"开发部","销售部","保洁部","售后部","总经办"};

        Random random=new Random();
        List persions = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            Persion persion = new Persion();
            persion.setName("sam" + i);
            persion.setDeptName(depts[random.nextInt(4)]);
            persion.setAge(random.nextInt(30)+15);
            persion.setSalary(random.nextInt(1000)+2000);
            persion.setHireTime(System.nanoTime());
            persions.add(persion);
        }
        mongoService.saveAll(persions);
    }
    //查找各部门工资总和
    @Test
    public void testSumSalaryByDept(){
        mongoService.sumSalaryByDept();
    }
    //查找各部门人数总和
    @Test
    public void testCountDept(){
        mongoService.countDept();
    }
    //查找各部门指定入职时间段(309663802686332)员工的工资总和
    @Test
    public void testSumSalaryByDeptAndTime(){
        mongoService.sumSalaryByDeptAndTime();
    }
    //查找各部门指定入职时间段(309663802686332)员工的人数总和
    @Test
    public void testCountDeptByDeptAndTime(){
        mongoService.countDeptByDeptAndTime();
    }
}

 

你可能感兴趣的:(mongoDB)