I am making a collection of user's data. This will be pretty basic consisting of user's email, user's password (hashed), and an array of strings.
{ email: '[email protected]', password: 'password hash', arr: [] }
I want to make sure that there can't be two inserts with the same email
. I read that the _id
of mongoDB is unique by default, and it uses some special data structure for improved performance.
How can I make sure that the email
remains unique, and if possible can I leverage the performance benefits provided by the _id
field ?
Edit: I also want to make sure that there are no null
values for email
and that there are no documents which do not contain the email
field.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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 .
Restrictions. 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.
Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.
Use unique keyword, or simply make _id value to be email.
db.collection.createIndex( { email: 1 }, { unique: true } )
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