MongoDB 测试数据,导入 MongoDB
https://gitee.com/shizidada/moose-resource/raw/master/shici_item.json
SpringBoot MongoDB 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.yml 添加配置
spring:
data:
mongodb:
host: localhost
port: 27017
database: shicimingju
创建实体和 mongodb 文档对应映射
/**
* @author taohua
* @Document 和 mongodb 集合名称对应
*
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Document(collection = "poetry_item")
public class PoetryEntity extends BaseEntity {
/**
* 主键 id
*/
@Id
private String id;
/**
* @Field mongodb 字段进行对应映射
*/
@Field("poetry_name")
private String poetryName;
@Field("poetry_content")
private String poetryContent;
@Field("poetry_author")
private String poetryAuthor;
@Field("poetry_num")
private String poetryNum;
@Field("type")
private String type;
}
增加
@Test
public void testSave() {
PoetryEntity poetryEntity = new PoetryEntity();
poetryEntity.setPoetryName("好诗词");
poetryEntity.setPoetryContent("今天不开心就止于此吧明天依旧光芒万丈");
poetryEntity.setPoetryAuthor("江景");
poetryEntity.setPoetryNum("1");
poetryEntity.setType("poetry");
poetryEntity.setCreateTime(LocalDateTime.now());
poetryEntity.setUpdateTime(LocalDateTime.now());
PoetryEntity save = mongoTemplate.save(poetryEntity);
log.info("{}", save);
}
修改
@Test
public void testUpdate() {
// 构建修改条件
Query query = Query.query(Criteria.where("poetry_author").is("江景"));
// 设置需要修改的字段
Update update = Update.update("poetry_name", "《好诗,好诗》");
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, PoetryEntity.class);
log.info("{}", updateResult);
}
删除
@Test
public void testDelete() {
Query query = Query.query(Criteria.where("poetry_author").is("江景"));
DeleteResult remove = mongoTemplate.remove(query, PoetryEntity.class);
log.info("{}", remove);
}
使用 remove 进行删除一点要设置条件
,不然会把整个集合数据全部删除
查询
@Test
public void testFind() {
Criteria criteria = Criteria.where("poetry_author").is("江景");
Query query = Query.query(criteria);
PoetryEntity poetryEntity = mongoTemplate.findOne(query, PoetryEntity.class);
log.info("{}", poetryEntity);
}
查询去重
@Test
public void testFindDistinct() {
/**
* String field, 查询字段
* Class<?> entityClass, 查询映射类型
* Class<T> resultClass 查询返回结果类型
*/
List<String> poetryAuthor =
mongoTemplate.findDistinct("poetry_author", PoetryEntity.class, String.class);
log.info("{}", poetryAuthor);
}
分页查询
@Test
public void testFindLimit() {
Criteria criteria = new Criteria();
Query query = Query.query(criteria);
// 方式一 skip + limit
query. skip(0).limit(10).with(Sort.by(Sort.Direction.DESC, "poetry_num"));
// 方式二 Pageable
//Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "poetry_num"));
//query.with(pageable);
List<PoetryEntity> poetryEntities = mongoTemplate.find(query, PoetryEntity.class);
log.info("{}", poetryEntities);
}
聚合查询
根据诗人名字分组
@Test
public void testAggregation() throws JsonProcessingException {
Aggregation aggregation =
Aggregation.newAggregation(
Aggregation.group("poetry_author").count().as("totalCount"),
// 根据分组的字段做别名,mongodb 查询的默认在 _id 中
Aggregation.project("poetry_author", "totalCount")
.and("poetryAuthor")
.previousOperation()
//, Aggregation.limit(10)
);
log.info("{}", aggregation.toString());
AggregationResults<Document> poetryAggregation =
mongoTemplate.aggregate(aggregation, "poetry_item", Document.class);
List<Document> mappedResults = poetryAggregation.getMappedResults();
for (Document item : mappedResults) {
log.info("{}", objectMapper.writeValueAsString(item));
}
}
2020-12-08 11:44:58.407 INFO 36960 --- [main] com.moose.operator.PoetryEntityTest : {"totalCount":240,"poetryAuthor":"李白"}
2020-12-08 11:44:58.408 INFO 36960 --- [main] com.moose.operator.PoetryEntityTest : {"totalCount":60,"poetryAuthor":"杜甫"}
...