mongodb @aggregation 返回字段映射不上_Spring Boot 操作 MongoDB

本文介绍了在使用 Spring Boot 操作 MongoDB 时遇到的 @Aggregation 结果字段映射问题。通过导入 MongoDB 测试数据、配置 SpringBoot MongoDB 依赖和设置 application.yml,详细讨论了实体与 MongoDB 文档的映射。此外,还涵盖了增加、删除、查询、去重、分页查询以及聚合查询的操作,特别关注了根据诗人名字进行分组的聚合查询实践。
摘要由CSDN通过智能技术生成

63179b74bcd4a44122c6de17d478f700.png

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);
  }

b56d82aea84d9bfc3c3467da998cfbfa.png

bb7540224ec6456207992a1b74320176.png

修改

@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);
}

27028ef267008fd37a2d39c2191fbe66.png

删除

@Test
  public void testDelete() {
    Query query = Query.query(Criteria.where("poetry_author").is("江景"));
    DeleteResult remove = mongoTemplate.remove(query, PoetryEntity.class);
    log.info("{}", remove);
  }
使用 remove 进行删除一点要设置条件,不然会把整个集合数据全部删除

25d0960f261ab4d1a135f45b045a0749.png

查询

@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);
  }

21b0bc2308c0819f2d1ca79af36a1d7e.png

查询去重

@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);
  }

adfe1b2ed1e6f5b25725a9d538d46f96.png

e49306c1e9aedd926db24ccd5d299892.png

分页查询

@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":"杜甫"}
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值