0

Creating index via MongoShell

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

Creating CompoundIndex via spring application

@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? I checked After inserting atleast one document.

Thanks in advance.

1 Answer 1

2

Here is a working example I tried (creates a new collection, document and the compound index):

The 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:

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:

{
        "_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"
        }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.