java - 在 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 应用程序创建。上面的代码有什么问题?它们不是等价的吗?我检查了插入至少一个文档后。
提前致谢。
解决方案
这是我尝试的一个工作示例(创建一个新集合、文档和复合索引):
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
在 (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"
}
]
推荐阅读
- typescript - Typescript - 如何从可能值的数组中动态定义类型?
- python - 如何在 Keras 中使用 fit_generator() 平衡数据集?
- html - HTMLWebViewSource 视频全屏选项已禁用
- node.js - 在 handleFormSubmit 之后 React Checkbox 总是返回 false
- c# - 如何在 MVVM 中使用带有 ObservableCollection 和 List 的搜索栏
- google-sheets - 如何在 Google 表格中反转 INDEX 公式
- linux - 可以在没有内核模块的情况下使用 dpdk 吗?
- javascript - 从父组件将道具传递给 UseEffect 钩子
- python - 如何使用 selenium 查找输入
- sql - 查询 R 机器学习服务 - 在 Where 子句中过滤类别