如何在动态Mongo集合上以编程方式创建索引?(使用Java Spring Data MongoDB)

huangapple go评论108阅读模式
英文:

How to create an index programmatically for a dynamic Mongo collection? ( Java Spring Data MongoDB )

问题

这里是你的翻译内容:

  1. @Getter
  2. @Setter
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. @Document(collection = "#{@dateService.getCurrentDate()}")
  6. @JsonInclude(JsonInclude.Include.NON_NULL)
  7. public class LogDocument {
  8. private ObjectId _id;
  9. private String log;
  10. private String key;
  11. }

正如你所见,我的集合名称是根据日期动态生成的,例如 2020-10-05

我想在 "key" 字段上创建一个唯一索引。怎么做?

当集合名称固定时,我可以在 MongoDB 配置类中简单地执行以下操作:

  1. mongoTemplate.indexOps("{collection name}").ensureIndex(indexDefinition.unique());

但由于集合是动态的,我需要一种触发 PostConstruct 的方式,每次创建新集合时我都可以在其中创建索引。

英文:

I need help with this, here is my document class:

  1. @Getter
  2. @Setter
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. @Document(collection = "#{@dateService.getCurrentDate()}")
  6. @JsonInclude(JsonInclude.Include.NON_NULL)
  7. public class LogDocument {
  8. private ObjectId _id;
  9. private String log;
  10. private String key;
  11. }

As you can see my collection name is dynamic depending on date, e.g. 2020-10-05.

I want to create a unique index on the key. HOW?

When the collection name is fixed I can simply do the following in the mongo Configuration class:

  1. mongoTemplate.indexOps("{collection name}").ensureIndex(indexDefinition.unique());

but since the collection is dynamic, I need a way to trigger a PostConstruct for every time a new collection is created so that I can create the index.

答案1

得分: 0

答案就是使用注解

  1. @Getter
  2. @Setter
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. //对于复合索引:
  6. @CompoundIndexes({
  7. @CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
  8. })
  9. @Document(collection = "#{@dateService.getCurrentDate()}")
  10. @JsonInclude(JsonInclude.Include.NON_NULL)
  11. public class LogDocument {
  12. private ObjectId _id;
  13. private String log;
  14. //对于一个字段的唯一索引:
  15. // @Indexed(unique = true)
  16. private String key;
  17. private String app;
  18. }
英文:

The answer is simply using annotations

  1. @Getter
  2. @Setter
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. //For Compound index:
  6. @CompoundIndexes({
  7. @CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
  8. })
  9. @Document(collection = "#{@dateService.getCurrentDate()}")
  10. @JsonInclude(JsonInclude.Include.NON_NULL)
  11. public class LogDocument {
  12. private ObjectId _id;
  13. private String log;
  14. //For a unique index on one field:
  15. // @Indexed(unique = true)
  16. private String key;
  17. private String app;
  18. }

huangapple
  • 本文由 发表于 2020年10月6日 17:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64222633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定