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?
MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index. You may not specify a unique constraint on a hashed index.
First, use Indexed annotation above of your field in your model as shown below: @Indexed(unique = true) private String email; Also, you should programmatically define your index. You should use the below code when defining your MongoTemplate .
Introduction to MongoDB Unique. MongoDB's Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data.
You can also enforce a unique constraint on compound indexes. If you use the unique constraint on a compound index, then MongoDB will enforce uniqueness on the combination of the index key values. The created index enforces uniqueness for the combination of groupNumber , lastname , and firstname values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With