我正在使用Spring Boot 2.0.0.M3。我有以下对象结构:
@Document(collections="note")
public class Note {
String id;
@Indexed(background=true,unique=true)
String requestid;
}
@Document(collection="noteExpression")
public class NoteExpression {
public static class Error {
private DateTime dateTime = DateTime.now();
private Note note;
private String exception;
}
String id;
//Some other fields
Error error;
}
在NoteExpression的对象中,我需要在发生意外情况时存储错误信息。一切似乎都很好。但问题是Mongo将为NoteExpression.Error中的嵌套属性Note创建一个唯一索引。
请参阅下面的Mongo命令的结果:
>db.noteExpression.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.noteExpression"
},
{
"v" : 2,
"unique" : true,
"key" : {
"errors.note.requestid" : 1
},
"name" : "errors.note.requestid",
"ns" : "test.noteExpression",
"background" : true
}
]
我的系统需要在Note文档上使用unique的唯一索引,但我不想在NoteExpression的文档上使用唯一索引。有没有办法避免在NoteExpression上创建索引?
答案 0 :(得分:1)
MongoDB索引包括设计的嵌套(当然也包括引用的)文档。这通常是令人头痛的问题,我到目前为止唯一的解决方案是通过在保存/插入操作中对其进行编码来实现唯一性约束,因此您必须首先查询数据库,检查前置条件,然后保存/插入满足前提条件。我将进一步研究它,看看Spring-Data是否为此提供了一些工作方法。