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

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

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

问题

这里是你的翻译内容:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
    private ObjectId _id;
    private String log;
    private String key;
}

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

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

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

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

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

英文:

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

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
    private ObjectId _id;
    private String log;
    private String key;
}

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:

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

答案就是使用注解

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
//对于复合索引:
@CompoundIndexes({
        @CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
})
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
    private ObjectId _id;
    private String log;
    //对于一个字段的唯一索引:
    // @Indexed(unique = true)
    private String key;
    private String app;
}
英文:

The answer is simply using annotations

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
//For Compound index: 
@CompoundIndexes({
        @CompoundIndex(name = "key_app", def = "{'key' : 1, 'app': 1}")
})
@Document(collection = "#{@dateService.getCurrentDate()}")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LogDocument {
    private ObjectId _id;
    private String log;
    //For a unique index on one field: 
    // @Indexed(unique = true)
    private String key;
    private String app;
}

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:

确定