2

I am using Spring Boot 2.0.0.M3. And I have the following object structure:

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

In the object of NoteExpression, I need to store the error information when something unexpected occurs. Everything seems to be fine. But the problem is Mongo will create a unique index for the nested property Note in NoteExpression.Error.

See the result of the Mongo command below:

>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
    }
]

Unique index for requestid on the documents of Note is necessary in my system, but I don't want the unique index on the documents of NoteExpression. Is there any way to avoid creating the index on NoteExpression?

1 Answer 1

2

MongoDB indexes include the nested (and of course also the referenced) documents by design. It is often a headache and the only solution that I have found until now is to implement the uniqueness constraint by coding it in the save/insert operations, so you have to query the database first, check the preconditions, and then save/insert if the preconditions are met. I will investigate it further to see if Spring-Data provides some workarround for this.

Sign up to request clarification or add additional context in comments.

1 Comment

Refer this: stackoverflow.com/a/47830677. Using a @Reference on Nested Object helps

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.