首页 > 解决方案 > 在 Spring Data MongoDB 中创建复合索引的问题

问题描述

通过 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 创建,但不能通过 spring 应用程序创建。上面的代码有什么问题?它们不是等价的吗?我检查了插入至少一个文档后。

提前致谢。

标签: javaspringmongodbspring-data-mongodb

解决方案


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

CarPOJO 类:

@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在 (new) : 集合中创建文档的应用程序代码:

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"
        }
]

推荐阅读