在 Spring 数据 MongoDB 中创建复合索引时出现问题
Problem creating compound index in 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 application.What 在上面的代码中出错?它们不是等价的吗?
我检查了插入至少一个文档后。
提前致谢。
这是我试过的一个工作示例(创建一个新的集合、文档和复合索引):
Car
POJOclass:
@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...
}
创建文档的应用程序代码在(new)car
: collection:
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"
}
]
通过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 application.What 在上面的代码中出错?它们不是等价的吗? 我检查了插入至少一个文档后。
提前致谢。
这是我试过的一个工作示例(创建一个新的集合、文档和复合索引):
Car
POJOclass:
@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...
}
创建文档的应用程序代码在(new)car
: collection:
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"
}
]