简体   繁体   English

在 Spring 数据 MongoDB 中创建复合索引时出现问题

[英]Problem creating compound index in Spring Data MongoDB

Creating index via MongoShell通过 MongoShell 创建索引

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

Creating CompoundIndex via spring application通过 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;
}

I was able to create via Mongo shell but not thourgh spring application.What's wrong in the above code?Are n't they equivalent?我能够通过 Mongo shell 创建,但不能通过 spring 应用程序创建。上面的代码有什么问题?它们不相等吗? I checked After inserting atleast one document.我检查了插入至少一个文档后。

Thanks in advance.提前致谢。

Here is a working example I tried (creates a new collection, document and the compound index):这是我尝试的一个工作示例(创建一个新集合、文档和复合索引):

The Car POJO class: Car POJO class:

@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...
}

The application code to create a document in the (new) car : collection:在(新) car中创建文档的应用程序代码:集合:

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

The result document verified from the mongo shell:mongo shell 验证的结果文档:

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

The indexes:指标:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM