java - 如何在 Spring Boot 中将 Java 实体映射到多个 MongoDB 集合并为两个集合使用不同的索引?

标签 java mongodb spring-boot

假设我有一个 pojo 类:

public class event {
  String eventId;
  String date;
  String state;
}

我想将我的事件类保存在 MongoDB 中的 2 个单独的集合中。

我可以使用 mongoTemplate 来实现此目的:

mongoTemplate.save(event, "collection_1");
mongoTemplate.save(event, "collection_2");

但是我遇到了问题,因为集合需要有不同的方式来处理文档。

  1. 第一个集合应将每个事件存储为新的 文档。但文档应在 x 秒后过期。
  2. 第二个集合应该只存储给定的最新条目 事件ID

使用注释,我可以通过以下方式分别实现 1. 和 2.:

标准 1。

@Document
public class event {
  String eventId;
  @Indexed(expireAfterSeconds = x)
  String date;
  String state;
}

标准 2。

@Document
public class event {
  @Id
  String eventId;
  String date;
  String state;
}

我找不到同时实现这两个标准的好方法。

我知道我可以创建另外 2 个类,它们具有与事件类相同的字段,但具有不同的注释,并且具有一个将事件作为参数的构造函数。但对于所有重复的代码来说,这确实不是一个好的解决方案。

有没有更优雅的解决方案来解决这个问题?

最佳答案

所以我终于找到了我的问题的答案。我会将其发布在这里,以防其他人遇到同样的问题。

技巧是通过配置文件而不是使用注释来设置索引。

@Configuration
@DependsOn("mongoTemplate")
public class MongoCollectionConfiguration {

    private final MongoTemplate mongoTemplate;

    @Autowired
    public MongoCollectionConfiguration(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @PostConstruct
    public void initIndexes() {
        mongoTemplate.indexOps("collection_1")
            .ensureIndex(
                new Index().on("location.timestamp", Sort.Direction.DESC).expire(604800)
            );
        mongoTemplate.indexOps("collection_2")
            .ensureIndex(
                new Index().on("location.timestamp", Sort.Direction.DESC).unique()
            );    
    }

我希望这对将来的人有所帮助,当然我愿意接受任何改进!

关于java - 如何在 Spring Boot 中将 Java 实体映射到多个 MongoDB 集合并为两个集合使用不同的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399296/

相关文章:

mongodb - 如何在kubernetes中包含带有mongo图像的数据

java - 在几个小时的范围内从昨天获取纪元时间

java - 字节码生成的访问对象与 GenerationMethodAccessor

java - JAVA中的动态Json解析并找到键和值对?

Java,矩阵溢出

java - 如何建立 Android Studio 与 mongoDB 的连接?

python - 在 Mongoengine 中使用键作为值

java - 仅最后一个索引值被插入到 Excel 工作表中

spring-boot - 有没有办法知道Axon框架何时为 'ready'

MySQL/JPA 字段没有默认值错误,即使该字段位于类层次结构中的不同类中