Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB Indexed(unique=true)

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?

like image 538
chubbsondubs Avatar asked Dec 16 '12 20:12

chubbsondubs


People also ask

Are indexes unique in MongoDB?

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.

How do you make a unique field in MongoDB spring boot?

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 .

What is unique true in MongoDB?

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.

How do you ensure uniqueness in MongoDB?

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.


1 Answers

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.

like image 184
Arthur Neves Avatar answered Sep 30 '22 15:09

Arthur Neves