在Spring Data MongoDB中创建复合索引的问题

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

通过MongoShell创建索引

db.car.createIndex({brand:1 , model:1 , colour:1 ,fuelTypes:1},{unique:true})

通过spring应用程序创建CompoundIndex

@Document
@CompoundIndex(def = "{ 'brand':1 , 'model':1 , 'colour':1 , 'fuelTypes':1 }",unique = true)
public class Car {

    private String brand;
    private String model;
    private List<FuelType> fuelTypes;
    private String colour;
}

我能够通过Mongo shell创建,但无法通过thourgh spring应用程序创建。以上代码有什么问题?它们不是等效的吗?插入至少一个文档后,我检查了。

提前感谢。

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

这是我尝试过的一个工作示例(创建一个新的集合,文档和复合索引):

Car POJO类:

@CompoundIndex(name = "car-cmp-idx", def = "{'brand': 1, 'model': 1}", unique = true)
@Document
public class Car {

    private String brand;
    private String model;
    private String colour;

    public Car() {

    }
    public Car(String brand, String model, String colour) {
        this.brand = brand;
        this.model = model;
        this.colour = colour;
    }

    // get/set methods. etc...
}

在(新)car:集合中创建文档的应用程序代码:

MongoOperations ops = new MongoTemplate(MongoClients.create(), "test");
Car car = new Car("Ford", "Model T", "Black");
ops.insert(car);

mongo shell验证的结果文档:

{
        "_id" : ObjectId("5ed46f4960c3f13e5edf43b6"),
        "brand" : "Ford",
        "model" : "Model T",
        "colour" : "Black",
        "_class" : "com.example.demo.Car"
}

索引:

[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.car"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "brand" : 1,
                        "model" : 1
                },
                "name" : "car-cmp-idx",
                "ns" : "test.car"
        }
]
© www.soinside.com 2019 - 2024. All rights reserved.