10

I'm having a lot of problems with Spring Data and MongoDB when it comes to an Indexed field.

I've gone over the docs, but they aren't very good at explaining the difference between @Indexed(unique=true) and @Indexed(unique=false).

I have a field that I wanted indexed so I can execute fast queries against it. In this case it's email address which generally should be unique, but it's possible for the emailAddress to be null for a period.

However, once one record as a null emailAddress I can't have any other records with a null emailAddress. Spring Data refuses to insert any additional records with null emailAddresses. And it fails to throw anything that it didn't work.

Right now I have it set to unique=true, but I'm contemplating setting it to unique=false to get around this problem.

Will this fix the problem?

And what other problems could I be adding by relaxing this?

Will MongoDB allow me to have multiple email addresses that are equal and still be fast at querying?

1 Answer 1

14

From mongodb docs: http://docs.mongodb.org/manual/core/indexes/#unique-indexes

So if you have a unique key, don't set it to null.

To be honest, in your use case(email field), I believe you don't need to use unique key, you could use sparse key, instead, so, docs that don't have email wont take up your btree index, which is going to save you space, and increase the lookup speed.

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.