MongoTemplate讀寫操作與創建索引

1、簡單查詢數據

		Query query = new Query();
        Criteria criteria = Criteria.where("userId").is(userId);
        query.addCriteria(criteria).limit(1);
        List<DTO> dtoList = mongoTemplate.find(query,
            DTO.class, "xxx");
        // xxx爲collectionName

需要特別注意DTO中的數據類型要與mongoDB中的類型一致,如果不一致,比如String與Long會導致查不到數據
2、分頁查詢

		Query query = new Query();
        Criteria criteria1 = null;
        Criteria criteria2 = null;
        Criteria criteria3 = null;
        try {
            if (!Strings.isNullOrEmpty(keyword)) {
                criteria1 = Criteria.where("keyword").regex(keyword);
            }
            if (!Strings.isNullOrEmpty(text)) {
                criteria2 = Criteria.where("text").regex(text);
            }
            if (!Strings.isNullOrEmpty(createTimeStart)) {
                criteria3 = Criteria.where("createTime").gte(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeStart));
            }
            if (!Strings.isNullOrEmpty(createTimeEnd)) {
                if (criteria3 != null) {
                    criteria3.lte(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeEnd));
                } else {
                    criteria3 = Criteria.where("createTime").lte(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createTimeEnd));
                }
            }
            if (criteria1 != null || criteria2 != null || criteria3 != null) {
                Criteria criteria = new Criteria();
                List<Criteria> nonNull = Lists.newArrayList();
                if (criteria1 != null) {
                    nonNull.add(criteria1);
                }
                if (criteria2 != null) {
                    nonNull.add(criteria2);
                }
                if (criteria3 != null) {
                    nonNull.add(criteria3);
                }
                if (nonNull.size() > 1) {
                    criteria.andOperator(nonNull.toArray(new Criteria[]{}));
                }
                if (nonNull.size() == 1) {
                    criteria = nonNull.get(0);
                }
                query.addCriteria(criteria);
            }
            query = query.with(new Sort(Sort.Direction.DESC, "createTime")).skip(pageInfoDto.getStartRow()).limit(pageInfoDto.getPageSize());
            List<DTO> dtoList = mongoTemplate.find(query, DTO.class, "xxx");

以上即可實現分頁查詢

3、數據新增

 				DTO dto= new DTO();
                dto.setId(1111);
                ....
                mongoTemplate.save(dto, "xxx");

4、創建索引

ListIndexesIterable<Document> indexList = mongoTemplate
                .getCollection("xxx").listIndexes();
        //先檢查是否存在索引,特殊業務應用,一般不需要這一步        
        for (Document document : indexList) {
            Object key = document.get("key");
            if (null != key && key instanceof Document) {
                Document keyDocument = (Document) key;
                if (keyDocument.containsKey("userId")) {
                    LoggerUtil.info("xxx userId exist index already");
                    return false;
                }
            }

        }
		
		//該參數爲索引的屬性配置
        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        indexOptions.name("idx_userId");

        String resultStr = mongoTemplate.getCollection("xxx")
        		// Document key爲索引的列名稱,value爲索引類型,在userId上創建hashed類型索引
                .createIndex(new Document("userId", "hashed"), new IndexOptions().background(false).name("idx_userId"));

        LoggerUtil.info("xxx add index idx_userId result : {}", resultStr);
        return true;

以上即可完成創建索引的操作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章