mongo操作工具类(索引创建等)

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ft.monitoring.management.OnlineApplication;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * mongo数据库工具类
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = OnlineApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("my")
@Rollback(value = false)
public class MongoUtil {

    private MongoTemplate mongoTemplate;

    /**
     * 创建查询索引
     */
    @Test
    public void createIndex(){
        List<IndexModel> indexModels = new ArrayList<>();
        //组合索引
        BasicDBObject index1 = new BasicDBObject();
        //"name"->索引列  1/-1 正序/倒序
        index1.put("name",1);
        index1.put("age",1);
        index1.put("birthday",-1);
        //添加配置
        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        //索引名称
        indexOptions.name("name_age_birthday");
        indexModels.add(new IndexModel(index1,indexOptions));
        System.err.println("name_age_birthday 开始创建索引");
        mongoTemplate.getCollection("user_info").createIndexes(indexModels);
    }

    /**
     * 创建失效索引
     */
    @Test
    public void mongoCreateExpireIndex(){
        List<IndexModel> indexModels = new ArrayList<>();
        //组合索引
        BasicDBObject index1 = new BasicDBObject();
        //失效列
        index1.put("updateTime",1);
        //添加配置
        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        indexOptions.name("expireIndex_updateTime");
        //失效时间->超过(当前时间-(365*24*60*60)秒)的作为失效数据自动删除
        indexOptions.expireAfter(31536000l, TimeUnit.SECONDS);
        indexModels.add(new IndexModel(index1,indexOptions));
        System.err.println("expireIndex_updateTime 开始创建失效索引");
        mongoTemplate.getCollection("base_data_test").createIndexes(indexModels);
    }

    /**
     * 查询方法1->使用封装的进行查询
     * 当数据量很多时,查询结果转为UserInfo耗时很高,可能会导致内存崩溃
     */
    @Test
    public void mongoSearch1(){
        System.err.println("==========开始->\t"+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss.sss"));
        //根据索引查询
        Criteria criteria1 = Criteria.where("name").is("张三");
        criteria1.and("age").is(18);
        criteria1.and("birthday").lte(dateToISODate(DateUtil.parse("2022-01-01 00:00:00","yyyy-MM-dd HH:mm:ss")))
                .gte(dateToISODate(DateUtil.parse("2021-01-01 00:00:00","yyyy-MM-dd HH:mm:ss")));
        Query query1 = new Query();
        query1.addCriteria(criteria1);
        List<UserInfo> list1 = mongoTemplate.find(query1,UserInfo.class,"user_info");
        System.err.println("==========结束->\t"+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss.sss"));
        System.err.println("数量"+list1.size());
    }

    /**
     * 原生document查询
     * 查询mongo原生的文档,类似json对象的使用方法,在数据量多的情况下,可以减少内存消耗
     */
    @Test
    public void mongoSearch2(){
        System.err.println("==========开始->\t"+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss.sss"));
        List<Bson> filterList = new ArrayList<>();
        filterList.add(Filters.in("name","张三"));
        filterList.add(Filters.eq("age",18));
        filterList.add(Filters.gte("birthday",dateToISODate(DateUtil.parse("2022-06-28 17:07:44","yyyy-MM-dd HH:mm:ss"))));
        filterList.add(Filters.lte("birthday",dateToISODate(DateUtil.parse("2022-06-28 17:07:44","yyyy-MM-dd HH:mm:ss"))));
        FindIterable<Document> documentFindIterable = mongoTemplate.getCollection("user_info").find(Filters.and(filterList));
        MongoCursor<Document> cursor = documentFindIterable.iterator();
        while (cursor.hasNext()){
            Document document = cursor.next();
            System.err.println(JSON.toJSONString(document));
        }
    }

    /**
     * 删除数据
     */
    @Test
    public void deleteTest(){
        DeleteResult result = mongoTemplate.remove(new Query(Criteria.where("name").is("张三")), "user_info");
        System.err.println("删除数据数量为:"+result.getDeletedCount());
    }


    public Date dateToISODate(Date dateStr){
        Date strToDate = null;
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            strToDate = sdf.parse(sdf.format(dateStr));
        }catch (Exception e){
            e.printStackTrace();
        }
        return strToDate;
    }

    /**
     * 用户信息
     */
    class UserInfo{
        private String name;
        private Integer age;
        private String address;
        private Date birthday;
        private Date createTime;
        private Date updateTime;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public Date getBirthday() {
            return birthday;
        }

        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }

        public Date getCreateTime() {
            return createTime;
        }

        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }

        public Date getUpdateTime() {
            return updateTime;
        }

        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    }
}

 

posted @ 2022-10-05 10:52  雨梦大木  阅读(634)  评论(0编辑  收藏  举报