使用Spring时如何更新MongoDb中的索引?

问题描述 投票:0回答:1

假设我的课程带有以下注释

@Data
@CompoundIndex(
    name = "unique_name_with_age",
    def = "{ 'firstName':1 , 'lastName':1 }",
    unique = true)
@Document
public class Person {

我相信上述意味着

firstName
lastName
的组合应该始终是唯一的。

现在如果我想在此约束中包含另一列会发生什么。假设我现在想要

@Data
@CompoundIndex(
    name = "unique_name_with_age",
    def = "{ 'firstName':1 , 'lastName':1, 'ssn':1 }",
    unique = true)
@Document
public class Person {

所以我希望在唯一约束中考虑

ssn
字段。我的问题是,我该如何进行此更新?

在像 postgres 这样的典型 RDBMS 中,我需要在数据库上运行一个命令来创建这个唯一的约束,如果需要,运行迁移脚本以确保现有数据不会违反这个新的约束。

但是我不熟悉 MongoDB,所以不知道如何在使用 Spring data Mongodb 注释时进行此类更新。

mongodb spring-data-mongodb
1个回答
0
投票

一种解决方案是使用 Mongock 进行迁移。然后您需要包含一个类似于以下代码的 ChangeUnit

@ChangeUnit(id = "...", order = "0", author = "...")
public class PersonUpdater {
...
@Execution
public void changeSet() {
    //This will query all the existing Person and save them again (this should update the index)
    mongoTemplate.stream(new Query(), Person.class).forEach(person-> {
            mongoTemplate
                    .save(person);
        });
    }
....
}

如果您想进一步更新架构,您可以将 mongock 变更集放在单独的模块中,并开始使用您检索和保存的实体版本:

@Document
public class PersonV1 {}

@Document
public class PersonV2 {}

@ChangeUnit(id = "...", order = "0", author = "...")
public class PersonUpdater {
...
@Execution
public void changeSet() {
    //This will query all the existing Person and save them again (this should update the index)
    mongoTemplate.stream(new Query(), PersonV1.class).forEach(person-> {
            PersonV2 personv2 = new PersonV2(...)
            mongoTemplate
                    .save(personv2);
        });
    }
....
}
© www.soinside.com 2019 - 2024. All rights reserved.